Skip to content

Detect initial theme #27

@danosaure

Description

@danosaure

Use browser to detect the initial theme.

React solution

const useThemeDetector = () => {
    const getCurrentTheme = () => window.matchMedia("(prefers-color-scheme: dark)").matches;
    const [isDarkTheme, setIsDarkTheme] = useState(getCurrentTheme());  
    const mqListener = (e) => setIsDarkTheme(e.matches);
    
    useEffect(() => {
      const darkThemeMq = window.matchMedia("(prefers-color-scheme: dark)");
      darkThemeMq.addListener(mqListener);
      return () => darkThemeMq.removeListener(mqListener);
    }, []);
    return isDarkTheme;
}

and use

const CurrentThemeComponent = () => {
  const isDarkTheme = useThemeDetector();
  return (
   <p>Current Theme is: {isDarkTheme ? "dark": "light"}</p>
  );
}

In Chrome debug console, got to ... , More tools, Rendering, then change: Emulate CSS media feature prefers-color-schema to desired value.

CSS option

Using CSS would force the app to stay within a certain theme until it is changed, approach only documented, but would not be a viable solution:

@media (prefers-color-scheme: light) {
  body {
    background: #FFF;
    color: #333;
  }
}
@media (prefers-color-scheme: dark) {
  body {
    background: #333;
    color: #FFF;
  }
}

Source

Based on document: https://medium.com/hypersphere-codes/detecting-system-theme-in-javascript-css-react-f6b961916d48

Metadata

Metadata

Assignees

Labels

enhancementNew feature or request

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions