I have a custom collapsible FAQ component that is based on the height of the element when it's expanded and vice versa.
import { useState, useRef, useEffect } from "react";
export default FAQItem({title, description}: FAQItemProps) {
const [isOpen, setIsOpen] = useState(false);
const heightRef = useRef<HTMLDivElement>(null);
const collapsible = () => (!isOpen ? setIsOpen(true) : setIsOpen(false));
useEffect(() => {
!isOpen
? (heightRef.current!.style.height = "96px")
: (heightRef.current!.style.height = `${offsetHeight}px`)
}, [isOpen]);
return(
<div ref={heightRef}>
<h2 onClick={collapsible}>{title}</h2>
<p>{description}</p>
</div>
)
}
Because I'm dealing with TypeScript, some of the already answered solutions I could find unfortunately doesn't have anything TypeScript-related answered and won't fly with TS and had to add type definitions. And it returned with error Cannot find name "offsetHeight"., and clientHeight does the same thing too.
I've tried adding any to offsetHeight, including:
declare const window: Window & typeof globalThis & {
offsetHeight: number | any;
}
...and as expected, the error went away but it didn't work - the height didn't change and and won't expand.
Nevertheless, all the solutions I could find unfortunately has no TypeScript-related answers regarding getting the width or height of an element on a React TypeScript project - all of them are just plain React questions without TypeScript, and I prefer to not use any external libraries of any kind either.