1 | initial version |
To enable both the system preference dark mode and the ability for users to switch between this theme and the current one in a React application, you can follow these steps:
Add a state variable to hold the current theme. For example, const [theme, setTheme] = useState('light')
.
Create a function to toggle the theme based on user preference. This can use the window.matchMedia
API to detect system preference, and set the theme accordingly. For example:
const toggleTheme = () => {
const prefersDarkMode = window.matchMedia('(prefers-color-scheme: dark)').matches;
setTheme(prefersDarkMode ? 'dark' : 'light');
}
useEffect
hook to listen for changes in the theme state, and update the CSS variables accordingly. For example:useEffect(() => {
const root = document.documentElement;
if (theme === 'dark') {
root.style.setProperty('--bg-color', 'black');
root.style.setProperty('--text-color', 'white');
} else {
root.style.setProperty('--bg-color', 'white');
root.style.setProperty('--text-color', 'black');
}
}, [theme]);
toggleTheme
function when clicked. For example:<button onClick={toggleTheme}>
Toggle Theme
</button>