Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

177
Visualizações
Alternador de tema Reaccionar: la elección no persiste al actualizar la página

Estoy tratando de aplicar el tema que el usuario eligió al valor inicial de useState(), pero cuando actualizo la página, la elección no se aplica. ¿Qué debo cambiar para que el valor persista durante la actualización de la página?

tema-alternar.js

 import React, { createContext, useState } from "react"; export const themes = { light: { background: "#41A9EC", fontColor: '#FFF' }, dark: { background: "#F9F9", fontColor: '#000' } } export const ThemeContext = createContext({}) export const ThemeProvider = (props) => { const [theme, setTheme] = useState(localStorage.themes) if(theme === themes.light) { localStorage.setItem('themes', JSON.stringify(themes.light)) } if(theme === themes.dark) { localStorage.setItem('themes', JSON.stringify(themes.dark)) } return ( <ThemeContext.Provider value={{ theme, setTheme }}> {props.children} </ThemeContext.Provider> ) }

tema-alternar-botón.js

 import React, { useContext } from "react" import { ThemeContext, themes } from "../../context/theme-toggler" import { Button } from "../button/button" export const ThemeTogglerButton = () => { const { theme, setTheme } = useContext(ThemeContext) return ( <div style={{ backgroundColor: theme.background, color: theme.fontColor }}> <Button onClick={() => setTheme(theme === themes.light ? themes.dark : themes.light)}>Theme Toggler</Button> </div> ) }

Gracias por adelantado.

about 4 years ago · Santiago Gelvez
2 Respostas
Responde à pergunta

0

import React, { createContext, useState } from "react"; export const themes = { light: { background: "#41A9EC", fontColor: '#FFF' }, dark: { background: "#F9F9", fontColor: '#000' } } export const ThemeContext = createContext({}) export const ThemeProvider = (props) => { const [theme, setTheme] = useState(localStorage.getItem("themes")) useEffect(() => { if(theme === themes.light) { localStorage.setItem('themes', JSON.stringify(themes.light)) } if(theme === themes.dark) { localStorage.setItem('themes', JSON.stringify(themes.dark)) } },[theme]) return ( <ThemeContext.Provider value={{ theme, setTheme }}> {props.children} </ThemeContext.Provider> ) }
about 4 years ago · Santiago Gelvez Relatório

0

Después de unos días, pude hacerlo funcionar. Estoy publicando la solución que encontré, para ayudar a otros con problemas similares.

archivo de botón de alternancia de tema:

 import React, { useContext } from "react" import { ThemeContext, themes } from "../../context/theme-toggler" import { Button } from "../button" export const ThemeTogglerButton = () => { const { theme, setTheme } = useContext(ThemeContext) function handleClick() { const localTheme = JSON.parse(localStorage.getItem("themes")) console.log(localTheme) setTheme(theme === themes.light ? themes.dark : themes.light) if (localTheme) { localStorage.setItem('themes', JSON.stringify(localTheme.name === 'light mode' ? themes.dark : themes.light)) } else { localStorage.setItem('themes', JSON.stringify(themes.light)) } } return ( <Button style={{ backgroundColor: theme.background, color: theme.fontColor }} onClick={() => handleClick()}>{ (theme === themes.light ? themes.dark.name : themes.light.name)} </Button> ) }

archivo de cambio de tema:

 import React, { createContext, useState, useEffect } from "react"; export const themes = { light: { name: 'light mode', background: '#41A9EC', fontColor: '#FFF' }, dark: { name: 'dark mode', background: '#212121', fontColor: '#AAB0BC' } } export const ThemeContext = createContext({}) export const ThemeProvider = (props) => { const [theme, setTheme] = useState([]) useEffect(() => { const localTheme = JSON.parse(localStorage.getItem("themes")) if (!localTheme) { localStorage.setItem('themes', JSON.stringify(themes.light)) setTheme(themes.light) } if (localTheme) { if (localTheme.name === 'light mode') { localStorage.setItem('themes', JSON.stringify(themes.light)) setTheme(themes.light) } if (localTheme.name === 'dark mode') { localStorage.setItem('themes', JSON.stringify(themes.dark)) setTheme(themes.dark) } } }, []) return ( <ThemeContext.Provider value={{ theme, setTheme }}> {props.children} </ThemeContext.Provider> ) }

Encuentre a continuación el repositorio de mi proyecto, donde actualmente estoy usando la solución anterior: https://github.com/Alex-Lima84/pokemon-react-api

about 4 years ago · Santiago Gelvez Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda