Ask Your Question

Revision history [back]

click to hide/show revision 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:

  1. Add a state variable to hold the current theme. For example, const [theme, setTheme] = useState('light').

  2. 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');
}
  1. Add a 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]);
  1. Add a button or other UI element to allow users to toggle the theme. This should call the toggleTheme function when clicked. For example:
<button onClick={toggleTheme}>
  Toggle Theme
</button>