PASSWORD RESET

Your destination for complete Tech news

How to detect dark mode in React JS?

1.7K 0
< 1 min read

To detect dark mode in a React application, you can use the window.matchMedia API with the prefers-color-scheme media query, similar to how you would do it in regular JavaScript. Here’s an example of how you can achieve this:

  1. Create a new React component or modify an existing one.
  2. Use the useEffect hook to listen for changes to the user’s color scheme preference.
  3. Update your component’s state based on whether dark mode is enabled.

Here’s how you can implement this:

import React, { useState, useEffect } from 'react';

function DarkModeDetector() {
  const [isDarkMode, setIsDarkMode] = useState(false);

  useEffect(() => {
    const darkModeMediaQuery = window.matchMedia('(prefers-color-scheme: dark)');

    const handleDarkModeChange = (event) => {
      setIsDarkMode(event.matches);
    };

    darkModeMediaQuery.addEventListener('change', handleDarkModeChange);
    setIsDarkMode(darkModeMediaQuery.matches);

    return () => {
      darkModeMediaQuery.removeEventListener('change', handleDarkModeChange);
    };
  }, []);

  return (
    <div>
      <p>Dark mode is {isDarkMode ? 'enabled' : 'disabled'}.</p>
    </div>
  );
}

export default DarkModeDetector;

In this example, the DarkModeDetector component uses the useEffect hook to add an event listener for changes to the prefers-color-scheme: dark media query. When the media query changes (which happens when the user toggles dark mode), the handleDarkModeChange function is called to update the state accordingly. The state variable isDarkMode is used to display whether dark mode is enabled or disabled.

Remember that this approach will work in modern browsers and devices that support the prefers-color-scheme media query. If you’re using a more complex theming or styling strategy in your React application, you might want to consider using a library like styled-components or ThemeProvider from @emotion/react to manage the appearance of your components based on the detected color scheme.

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.