Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

208
Views
React collapsing div animation with CSS

I don't really understand why my component doesn't work. I want to create a component which expand/collapse when you click the button. It works fine, but I have a problem with the animation. When I click the button, website crashes. This is my component:

import { useState, useRef, React } from 'react'

const Collapsible = ({ desc, text }) => {
    const [isOpen, setIsOpen] = useState(false);
    const parentRef = useRef();

  return (
    <div className='city'>
        <button className='toggle-btn' onClick={()=> {
            setIsOpen(!isOpen);
        }}>{text}</button>
        
        { isOpen && 
        <div 
        className="city-info" 
        ref={parentRef}
        style={isOpen ? {
            height: parentRef.current.scrollHeight + "px",
        }:{
            height: "0px",
        }}
        >{desc}</div>}
    </div>
  )
}

export default Collapsible

And this is the error I get:

Uncaught TypeError: Cannot read properties of undefined (reading 'scrollHeight')

Why is it undefined? After a long time of trying to do it by myself, I gave up and I did a step-by-step with tutorial and it works great in the tutorial.

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!