Company logo
  • Jobs
  • Bootcamp
  • About Us
  • For professionals
    • Home
    • Jobs
    • Courses
    • Questions
    • Teachers
    • Bootcamp
  • For business
    • Home
    • Our process
    • Plans
    • Assessments
    • Payroll
    • Blog
    • Calculator

0

53
Views
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>   
7 months ago · Juan Pablo Isaza
1 answers
Answer question

0

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')
7 months ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post job Plans Our process Sales
Legal
Terms and conditions Privacy policy
© 2023 PeakU Inc. All Rights Reserved.