How to detect dark mode theme in React Material UI

#react #material-ui

Last updated on Nov 22, 2020 by Suraj Sharma



In this tutorial, you will learn how you can use a custom React hook useMediaQuery provided by the react material ui core module to check if dark mode is enabled on your browser.



Using useMediaQuery() hook


React material ui core module @material-ui/core exports the useMediaQuery() custom hook to check whether a given CSS media query string is applied or not. It returns a boolean value.


To detect if dark theme is enabled we have to pass (prefers-color-scheme: dark) media query string as an argument to the useMediaQuery() hook


Example:


import React from 'react';
import useMediaQuery from '@material-ui/core/useMediaQuery';

const DetectDarkMode = () => {
  const isDarkModeEnabled = useMediaQuery('(prefers-color-scheme: dark)');

  return (
    <p>{`Dark mode is enabled: ${isDarkModeEnabled}`}</p>
  );
}


Related Solutions



Suraj Sharma is a JavaScript Software Engineer. He holds a B.Tech degree in Computer Science & Engineering from NIT Rourkela.