Answer the question
In order to leave comments, you need to log in
Why does the theme change only after the second click on the radio button?
To change the theme, I use the following code:
The function that handles the click on the radio button, which I pass to the button from the App component:
const onThemeToggleHandler = (theme, setTheme) => {
setTheme(theme == 'theme-dark' ? 'theme-light' : 'theme-dark')
}
const [theme, setTheme] = useState('theme-dark')
useEffect(() => {
document.querySelector('.App').classList.toggle(theme)
}, [theme])
Answer the question
In order to leave comments, you need to log in
How is the theme switched? The old class is removed, the new one is added. Let's see what you are doing:
useEffect(() => {
document.querySelector('.App').classList.toggle(theme)
}, [theme])
useEffect(() => {
const el = document.querySelector('.App');
el.classList.add(theme);
return () => el.classList.remove(theme);
}, [ theme ]);
Why manually change the class? This is "anti-React". Keep the theme in context, tie the render of the App component to a value from the context, change that value on click - the correct conventional way. And your version is fragile and generally stupid.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question