Component Recipes: React, focus an item in React when added to the DOM

Join the AI Workshop to learn more about AI and how it can be applied to web development. Next cohort February 1st, 2026

The AI-first Web Development BOOTCAMP cohort starts February 24th, 2026. 10 weeks of intensive training and hands-on projects.


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 by React.

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
  ...// rest of the input field attributes

Lessons in this unit:

0: Introduction
1: ▶︎ React, focus an item in React when added to the DOM
2: React, edit text on double-click
3: React: How to show a different component on click
4: Change the Heroicons SVG stroke width in React