React, focus an item in React when added to the DOM

By

Learn the simplest way to focus an input in React as soon as it is added to the DOM: just use the autoFocus attribute, with a capital F in your JSX.

~~~

To focus an input as soon as React adds it to the DOM, add the autoFocus attribute to it. That’s it, one attribute, no hooks needed.

Here’s how I got there. I had a modal with a simple form, with just an input field in it, and I wanted to put that element on focus as soon as the modal was added to the DOM.

I began thinking about many different ways to do so. Maybe using useEffect() to trigger an event when the component was added to the DOM, or using the ref prop to create a reference to the DOM element and call its focus() method. But then I realized I was thinking too complicated, and just using the autofocus HTML attribute on the element could work.

And it did. Remember that it is autoFocus in JSX, with the capital F:

<input
  autoFocus
  type="text"
  name="city"
/>

Why does this work in a modal?

In plain HTML, autofocus only fires when the page loads. My modal appears long after page load, so you’d expect it to do nothing.

React treats autoFocus differently. Instead of relying on the browser behavior, React calls focus() on the element when it mounts it. So it works every time the input enters the DOM, including a modal opening minutes after the page loaded.

Watch the casing

If you write autofocus all lowercase, React logs a warning in the console asking if you meant autoFocus, and the input doesn’t get focused. This one is easy to miss because the code looks correct if you’re used to HTML. Capital F, problem solved.

When you need the ref approach instead

autoFocus covers the “focus on mount” case. If you need to focus the input at some later moment, say after the user clicks a button, you need the ref:

const inputRef = useRef(null)

<input ref={inputRef} type="text" name="city" />

<button onClick={() => inputRef.current.focus()}>
  Edit city
</button>

Both are valid tools. For my modal, autoFocus was the one-line answer.

One last thing: use this on the field the user certainly wants to type in, like the single input of a search modal. Stealing focus on a regular page can be disorienting, especially for people using screen readers.

Tagged: React · All topics
~~~

Related posts about react: