Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

183
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!