All files / components ThemeChanger.js

87.5% Statements 7/8
50% Branches 4/8
66.66% Functions 2/3
85.71% Lines 6/7

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26          16x 16x     16x 8x     16x   8x                    
import { useTheme } from 'next-themes'
import { BsMoon, BsSun } from 'react-icons/bs'
import { useState, useEffect } from 'react'
 
export default function ThemeChanger() {
  const { theme, setTheme } = useTheme()
  const [isMounted, setIsMounted] = useState(false)
 
  // needed for rehydration mismatch between server/client
  useEffect(() => {
    setIsMounted(true)
  }, [])
 
  if (!isMounted) return null
 
  return (
    <button
      className="flex items-center w-7 h-7 bg-gray-900 p-2 cursor-pointer rounded hover:bg-gray-800 text-white dark:bg-periwinkle"
      aria-label={`toggle ${theme === 'dark' ? 'light' : 'dark'} mode`}
      onClick={() => setTheme(theme === 'dark' ? 'light' : 'dark')}
    >
      {theme === 'dark' ? <BsSun /> : <BsMoon />}
    </button>
  )
}