I want to select the theme value to change it based on localStorage value to set the light/dark theme, how can I do that in React?
I know I can use Ref hook in a component but how can I select a dom element in index.html?
Change <html theme="dark">
to <html class="dark">
, and then add separate .light
and .dark
CSS classes. You can then create a custom hook that you can import into the component that has the toggle functionality.
Here the custom hook (useToggleTheme
) initialises a state and returns a function. The function declares a new theme depending on the current state, changes the class on the document element (<html>
), and then sets the new state with that value. This function is what your button calls.
const { useState } = React;
function useToggleTheme() {
const [theme, setTheme] = useState('dark');
function toggleTheme() {
const newTheme = theme === 'dark' ? 'light' : 'dark';
document.documentElement.className = newTheme;
setTheme(newTheme);
}
return toggleTheme;
}
function Example() {
const toggleTheme = useToggleTheme();
return (
<div>
<button onClick={toggleTheme}>
Toggle theme
</button>
</div>
);
}
const node = document.getElementById('root');
const root = ReactDOM.createRoot(node);
root.render(<Example />);
.dark { background-color: darkgray; color: white; }
.light { background-color: white; color: darkgray; }
<html class="dark">
<body>
<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.2.0/umd/react.development.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.2.0/umd/react-dom.development.min.js"></script>
</body>
</html>