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?
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>
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With