Ref returns undefined or null in React [Solved]

avatar

Borislav Hadzhiev

Last updated: Apr 28, 2022

banner

Photo from Unsplash

Ref returns undefined or null in React [Solved] #

A React ref most commonly returns undefined or null when we try to access its current property before its corresponding DOM element is rendered. To get around this, access the ref in the useEffect hook or when an event is triggered.

App.js
import {useRef, useEffect} from 'react'; export default function App() { const ref = useRef(); console.log(ref.current); // 👈️ undefined here useEffect(() => { const el2 = ref.current; console.log(el2); // 👈️ element here }, []); return ( <div> <div ref={ref}> <h2>Hello</h2> </div> </div> ); }

The useRef() hook can be passed an initial value as an argument. The hook returns a mutable ref object whose .current property is initialized to the passed argument.

We didn't pass an initial value to useRef so its current property is set to undefined.

If we had passed null to the hook, its current property would be null if accessed immediately.

Notice that we have to access the current property on the ref object to get access to the div element on which we set the ref prop.

When we pass a ref prop to an element, e.g. <div ref={myRef} />, React sets the .current property of the ref object to the corresponding DOM node.

We used the useEffect hook because we want to make sure the ref has been set on the element and the element has been rendered to the DOM.

If we try to access the current property of the ref directly in the component, we would get undefined back because the ref hasn't been set up and the div element has not been rendered.

You can also access the current property of the ref in an event handler function.

App.js
import {useRef, useEffect} from 'react'; export default function App() { const ref = useRef(); console.log(ref.current); // 👈️ undefined here useEffect(() => { const el2 = ref.current; console.log(el2); // 👈️ element here }, []); const handleClick = () => { console.log(ref.current); // 👈️ element here }; return ( <div> <div ref={ref}> <h2>Hello</h2> </div> <button onClick={handleClick}>Click</button> </div> ); }

By the time the user clicks on the button, the ref has been set up and the corresponding element has been rendered to the DOM, so we can access it.

Conclusion #

A React ref most commonly returns undefined or null when we try to access its current property before its corresponding DOM element is rendered. To get around this, access the ref in the useEffect hook or when an event is triggered.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.