Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way of using the useState hook to toggle className in react?

I'm trying to implement a vertical ellipsis, whereby users can click on it (toggle) and select the actions they want to perform.

However, i understand that directly manipulating the DOM in react is not allowed. Because trying to toggle a classList throws the error - TypeError: Cannot read property 'classList' of null.

How can I make use of the useState hook to add/remove a className on toggle?

like image 416
Somtochukwu DB Avatar asked Dec 07 '25 15:12

Somtochukwu DB


1 Answers

Standard fair:

const [toggleClass, setToggleClass] = useState(false)

return <div className={toggleClass ? 'some-class' : ''} /> 

Using template literals:

const [toggleClass, setToggleClass] = useState(false)

return <div className={`some-class ${toggleClass ? 'some-class' :''}`} /> 

Using the popular classnames package:

import cx from 'classnames'

const Component = () => {
    const [toggleClass, setToggleClass] = useState(false)

    return <button className={cx('btn', {
        'btn--primary': toggleClass
    })}>Submit</button>

}

like image 130
Jay Kariesch Avatar answered Dec 09 '25 18:12

Jay Kariesch