How to reference a DOM element in React

By

Published · Updated

Tagged: React

Reference a DOM element in React with useRef(), pass refs to your own components with React 19's ref prop, keep refs for a list of items, and avoid the common null ref errors.

React usually manages the DOM for us.

Sometimes we need the underlying element. For example, we might need to focus an input, scroll to an item, measure an element, or connect a DOM-based library.

Use the useRef() hook for this:

import { useRef } from 'react'

export default function SearchForm() {
  const inputRef = useRef(null)

  function focusInput() {
    inputRef.current.focus()
  }

  return (
    <>
      <input ref={inputRef} />
      <button type="button" onClick={focusInput}>
        Focus the input
      </button>
    </>
  )
}

Passing inputRef to the ref attribute tells React to store the DOM element in inputRef.current.

I wrote more about the hook itself, including refs that hold values instead of elements, in How to use the useRef React hook.

When ref.current is available

React fills in ref.current after it updates the DOM, not while your component renders.

During the first render the element doesn’t exist yet, so ref.current is null. React also sets it back to null when the element is removed from the page.

That’s why you should read DOM refs in event handlers or effects, not in the body of the component:

import { useEffect, useRef } from 'react'

export default function SearchForm() {
  const inputRef = useRef(null)

  // Wrong: this runs during render, inputRef.current is null the first time
  // inputRef.current.focus()

  useEffect(() => {
    inputRef.current.focus()
  }, [])

  return <input ref={inputRef} />
}

Use optional chaining if the element might not be on the page, for example when it’s rendered conditionally:

inputRef.current?.focus()

Get a DOM element inside your own component

Passing a ref to one of your own components doesn’t work by default:

function MyInput({ value, onChange }) {
  return <input value={value} onChange={onChange} />
}

// inputRef.current stays null
<MyInput ref={inputRef} />

When you then call inputRef.current.focus(), you get an error like TypeError: Cannot read properties of null.

Your own components don’t expose the DOM nodes inside them unless you say so. In React 19 you do that by reading ref as a normal prop and passing it to the element:

function MyInput({ ref, ...props }) {
  return <input ref={ref} {...props} />
}

export default function SearchForm() {
  const inputRef = useRef(null)

  return (
    <>
      <MyInput ref={inputRef} placeholder="Search" />
      <button onClick={() => inputRef.current.focus()}>Focus</button>
    </>
  )
}

In React 18 and earlier you need to wrap the component in forwardRef(). It still works in React 19, but it’s not needed anymore, and React plans to deprecate it in a future release. See What’s new in React 19 for the other changes.

Expose only some methods

Sometimes you don’t want the parent to get the whole DOM element. With useImperativeHandle() you decide what ref.current contains:

import { useImperativeHandle, useRef } from 'react'

function MyInput({ ref, ...props }) {
  const realInputRef = useRef(null)

  useImperativeHandle(ref, () => ({
    focus() {
      realInputRef.current.focus()
    },
  }))

  return <input ref={realInputRef} {...props} />
}

Now the parent can call inputRef.current.focus(), and nothing else.

Refs for a list of items

You can’t call useRef() inside a map(), because hooks must be called at the top level of the component.

Instead, keep a Map in a single ref, and pass a function to ref. React calls this ref callback with the DOM node when the element is added:

import { useRef } from 'react'

export default function CatList({ cats }) {
  const itemsRef = useRef(new Map())

  function scrollToCat(cat) {
    itemsRef.current.get(cat.id)?.scrollIntoView({ behavior: 'smooth' })
  }

  return (
    <>
      {cats.map((cat) => (
        <button key={cat.id} onClick={() => scrollToCat(cat)}>
          {cat.name}
        </button>
      ))}

      <ul>
        {cats.map((cat) => (
          <li
            key={cat.id}
            ref={(node) => {
              itemsRef.current.set(cat.id, node)

              return () => {
                itemsRef.current.delete(cat.id)
              }
            }}
          >
            <img src={cat.imageUrl} alt={cat.name} />
          </li>
        ))}
      </ul>
    </>
  )
}

The function returned from the ref callback is a cleanup function. React 19 calls it when the element is removed, so the Map doesn’t keep nodes that are gone.

Before React 19, ref callbacks couldn’t return a cleanup function. React called the callback again with null instead, so you’d check for null and delete the entry there.

Watch out for implicit returns

With cleanup functions, whatever a ref callback returns matters. This arrow function returns the assignment by accident, and TypeScript rejects it in React 19:

<div ref={(node) => (instance = node)} />

Use curly braces so it returns nothing:

<div ref={(node) => { instance = node }} />

Also keep in mind that if you pass a new function on every render, React runs the cleanup and calls the new callback on every render too. And in Strict Mode, React runs ref callbacks twice in development.

Scroll to an element right after a state change

This looks right, but it scrolls to the item before the new one:

function handleAdd() {
  setTodos([...todos, newTodo])
  listRef.current.lastChild.scrollIntoView()
}

Setting state doesn’t update the DOM right away. When the next line runs, the new item isn’t there yet.

Wrap the state update in flushSync() from react-dom to make React update the DOM first:

import { flushSync } from 'react-dom'

function handleAdd() {
  flushSync(() => {
    setTodos([...todos, newTodo])
  })
  listRef.current.lastChild.scrollIntoView()
}

Don’t change the DOM that React manages

Focusing, scrolling and measuring are safe. Removing elements, adding children, or changing content that React renders is not.

React doesn’t know about those changes. The next time it updates that part of the page, the result can look wrong or crash. You can safely change parts of the DOM that React has no reason to update, like an empty <div> you hand to a chart library.

Refs are an escape hatch. Before using one, check if you can express the same behavior with props and state.

Want me to talk about your product? You can sponsor this site.

Related posts about react: