Home > database >  How do I add or remove class from HTML tag (using toggle) in React.js
How do I add or remove class from HTML tag (using toggle) in React.js

Time:04-28

Dear StackOverflow users. I need to make a dark mode using React.js and Tailwind, but when my dark mode icon is clicked, I need to add and remove the dark class from the HTML tag (in a toggle), but I am getting an error.

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>

Error

Cannot read properties of undefined (reading 'toggle')

CodePudding user response:

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];

CodePudding user response:

You can try this : <span id='darkmode' className={w-5 h-5 bg-white block cursor-pointer ${isDark ? dark : ''}} onClick={toggleDark}>

  • Related