Florie Anstett
Florie Anstett

Reputation: 1423

NextJS ref.current is null

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 ?

Upvotes: 1

Views: 2300

Answers (2)

Felipe
Felipe

Reputation: 12008

This scenario is common when using hooks that have dependencies, such as useEffect. The key here is to add your ref to the dependency list, so that it runs again when the component is mounted and the div is created:

function Component({ artwork }) {
    const [height, setHeight] = useState(-1);
    const ref = useRef();
 
    useEffect(() => {
        if(artwork && ref?.current) {
            console.log('setting');
            setHeight(ref.current.scrollHeight);
        }
    }, [artwork, ref]);
    
    return (
        <div ref={ref} className="some code">{height}</div>
    );
}

The problem is that in your original code, artwork is the only item in the dependency list, which means it will run when artwork is changed.

   ...
}, [artwork]);

I made this testable in CodeSandbox
(Note that the linter wants you to add height to the list of dependencies, but for this example I have left it out)

Upvotes: 0

dante
dante

Reputation: 1121

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

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

Upvotes: -1

Related Questions