Skip to content

Commit

Permalink
fix(theme): fix issues with theme switch (#14)
Browse files Browse the repository at this point in the history
  • Loading branch information
gdarchen authored Jul 3, 2024
1 parent 3d18bc8 commit d285455
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 3 deletions.
2 changes: 1 addition & 1 deletion src/components/header/Header.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ const header = tv({
base: 'fixed z-20 flex w-full translate-y-0 justify-between bg-background-light px-6 py-2 transition duration-300 dark:bg-background sm:px-12 sm:py-4',
variants: {
mobileMenu: {
true: 'bg-opacity-0',
true: 'bg-opacity-0 dark:bg-opacity-0',
false: 'bg-opacity-90 shadow-xl dark:bg-opacity-70',
},
},
Expand Down
19 changes: 17 additions & 2 deletions src/components/theme-switch/ThemeSwitch.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import React, { FC, useEffect } from 'react'
import React, { FC, useEffect, useState } from 'react'
import { HiOutlineMoon, HiSun } from 'react-icons/hi'
import { tv } from 'tailwind-variants'
import { useLocalStorage } from 'usehooks-ts'
Expand All @@ -9,14 +9,29 @@ const themeIcon = tv({

const ThemeSwitch: FC = () => {
const [theme, setTheme] = useLocalStorage('theme', 'dark')
const [isLight, setIsLight] = useState(theme === 'light')
const [mounted, setMounted] = useState(false)

useEffect(() => {
setIsLight(theme === 'light')
}, [theme])

// Trick to avoid hydration mismatch on SVG tags
useEffect(() => {
setMounted(true)
}, [])

useEffect(() => {
document.body.classList.remove('light', 'dark')
document.body.classList.add(theme)
}, [theme])

const handleThemeChange = () => {
setTheme(theme === 'light' ? 'dark' : 'light')
setTheme(isLight ? 'dark' : 'light')
}

if (!mounted) {
return null
}

return (
Expand Down
3 changes: 3 additions & 0 deletions tailwind.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,9 @@ import colors from 'tailwindcss/colors'
export default {
darkMode: 'class',
content: ['./src/**/*.{js,ts,jsx,tsx,mdx}'],
future: {
hoverOnlyWhenSupported: true,
},
theme: {
rotate: {
'-180': '-180deg',
Expand Down

0 comments on commit d285455

Please sign in to comment.