Skip to content

Commit

Permalink
Set initial theme from user's system settings
Browse files Browse the repository at this point in the history
  • Loading branch information
jeffslofish committed Sep 11, 2022
1 parent 5230002 commit 3cd157a
Showing 1 changed file with 21 additions and 8 deletions.
29 changes: 21 additions & 8 deletions components/Layout.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,18 @@ import classNames from 'classnames';
import { useEffect } from 'react';
import styles from './Layout.module.css';

function setMode(mode, setLocalStorage = false) {
if (mode === 'dark') {
document.documentElement.classList.add('dark');
} else {
document.documentElement.classList.remove('dark');
}

if (setLocalStorage) {
localStorage.setItem('theme', mode);
}
}

export function GradientBackground({ variant, className }) {
const classes = classNames(
{
Expand All @@ -16,15 +28,16 @@ export function GradientBackground({ variant, className }) {

export default function Layout({ children }) {
const setAppTheme = () => {
const darkMode = localStorage.getItem('theme') === 'dark';
const lightMode = localStorage.getItem('theme') === 'light';

if (darkMode) {
document.documentElement.classList.add('dark');
} else if (lightMode) {
document.documentElement.classList.remove('dark');
const localStorageTheme = localStorage.getItem('theme');
if (localStorageTheme) {
setMode(localStorageTheme);
} else {
if (window.matchMedia('(prefers-color-scheme: dark)').matches) {
setMode('dark', true);
} else {
setMode('light', true);
}
}
return;
};

const handleSystemThemeChange = () => {
Expand Down

0 comments on commit 3cd157a

Please sign in to comment.