'Reactjs use ref on parent element
I have this on reactjs in a functional component:
const searchTitle = useRef();
<FormGroup className={'filterItems p-3 active'} ref={searchTitle}>
<div onClick={()=> handleTitleToggle()}>
</div>
</FormGroup>
And want to toggle class on FormGroup via click on div.
const handleTitleToggle = () => {
searchTitle.current.classList.toggle('active')
}
But give me error:
TypeError: Cannot read properties of null (reading 'classList')
But if I use ref on div, it works fine, any idea?
<div ref={searchTitle} onClick={()=> handleTitleToggle()}>
</div>
Solution 1:[1]
if you are using MUI FormGroup Component be sure that it accept ref and when you have chain of props on you object use optional chaining to avoid errors like this
searchTitle?.current?.classList?.toggle('active')
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
