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.