Hello dear stackoverflow users. I need to make a darkmode using React.js and tailwindcss, but when my dark mode icon is clicked, I need to add and remove the dark class from the html tag (in the form of a toggle), but I am getting an error.
MY CODE :
const [isDark, setDark] = useState(false)
const toggleDark = () => {
setDark(!isDark)
const html = document.getElementsByTagName("html")
console.log(html);
html.classList.toggle("dark")
}
<span id='darkmode' className='w-5 h-5 bg-white block cursor-pointer' onClick={toggleDark}></span>
MY ERROR İS : Cannot read properties of undefined (reading ‘toggle’)
>Solution :
document.getElementsByTagName("html") actually returns an array. classList is not a property of an array, so it becomes undefined. In order to actually toggle it, get the first item of the array, which will be the html element.
const html = document.getElementsByTagName("html")[0];