Ask Your Question
4

What is the process 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?

asked 2022-09-12 11:00:00 +0000

ladyg gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
3

answered 2021-04-21 13:00:00 +0000

david gravatar image

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>
edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2022-09-12 11:00:00 +0000

Seen: 17 times

Last updated: Apr 21 '21