How to reference a DOM element in React

By

Learn how to reference a DOM element in a React function component with useRef(), then access the node through ref.current when you need a DOM API.

~~~

React usually manages the DOM for us.

Sometimes we need the underlying element. For example, we might need to focus an input 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.

React sets it to null before mounting the element and after removing it. Use optional chaining if the element might not be available:

inputRef.current?.focus()

Access DOM refs from event handlers or effects, not while rendering the component.

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

Tagged: React ยท All topics
~~~

Related posts about react: