Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do I add or remove class from html tag (using toggle) in React.js

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’)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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];
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading