Created
November 15, 2023 08:33
-
-
Save nwebpro/ab5c60ab136091b0942478756e82d334 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* eslint-disable react/prop-types */ | |
import { createContext, useEffect, useState } from "react"; | |
export const ThemeContext = createContext() | |
const ThemeProvider = ({ children }) => { | |
const [theme, setTheme] = useState('light') | |
useEffect(() => { | |
if (localStorage.getItem('theme') === null) { | |
localStorage.setItem('theme', 'light'); | |
} | |
}, []); | |
useEffect(() => { | |
const html = document.querySelector('html'); | |
if (localStorage.getItem('theme') === 'dark') { | |
html.classList.add('dark'); | |
setTheme('dark'); | |
} else { | |
html.classList.remove('dark'); | |
setTheme('light'); | |
} | |
}, [theme]); | |
const handleThemeSwitch = () => { | |
if (localStorage.getItem('theme') === 'light') { | |
setTheme('dark'); | |
localStorage.setItem('theme', 'dark'); | |
} else { | |
setTheme('light'); | |
localStorage.setItem('theme', 'light'); | |
} | |
}; | |
const themeInfo = { | |
theme, | |
setTheme, | |
handleThemeSwitch | |
} | |
return ( | |
<ThemeContext.Provider value={ themeInfo }> | |
{children} | |
</ThemeContext.Provider> | |
) | |
} | |
export default ThemeProvider |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment