Skip to content

Instantly share code, notes, and snippets.

@wobsoriano
Created July 5, 2021 09:11
Show Gist options
  • Save wobsoriano/db11c14f6742405c3dbb5f900c73b28f to your computer and use it in GitHub Desktop.
Save wobsoriano/db11c14f6742405c3dbb5f900c73b28f to your computer and use it in GitHub Desktop.
Solid Theme Provider for Tailwind/Windi
import { createContext, createEffect, createSignal, useContext } from 'solid-js'
const themeName = 'theme'
const html = document.querySelector('html')
function getInitialTheme() {
const isDark = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches
const storageTheme = localStorage.getItem(themeName)
if (storageTheme) return storageTheme
return isDark ? 'dark' : 'light'
}
const ThemeContext = createContext()
export function ThemeProvider(props) {
const [theme, setTheme] = createSignal(getInitialTheme())
createEffect(() => {
localStorage.setItem(themeName, theme())
if (theme() === 'dark') {
html.classList.add('dark')
} else {
html.classList.remove('dark')
}
})
const store = [
theme,
{
toggle() {
setTheme((prev) => prev === 'dark' ? 'light' : 'dark')
}
}
]
return <ThemeContext.Provider value={store}>{props.children}</ThemeContext.Provider>;
}
export function createTheme() {
return useContext(ThemeContext)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment