Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

176
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda