NextJS ref.current is null

Viewed 135

I'm trying to get the height of a div using useRef but I get an error "ref.current is null".
I imported useRef from React.

My code concerning ref :

    const [height, setHeight] = useState(0);
    const ref = useRef(null);

    useEffect(() => {
        artwork && setHeight(ref.current.scrollHeight)
    }, [artwork]);

And I added the ref to my div :

    <div
        ref={ref}
        className="some code"
            
    >

What am I missing ?

1 Answers

make sure check both ref and ref.current is not nullish.

 useEffect(() => {
   if(ref && ref.current) {
      artwork && setHeight(ref.current.scrollHeight)
   }
 }, [artwork]);
Related