React, focus an item in React when added to the DOM
How to focus an item in React as soon as added to the DOM`
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
Find a ton of Web Development projects to learn modern tech stacks
in practice in THE VALLEY OF CODE PRO
I wrote 16 books for beginner software developers,
DOWNLOAD THEM NOW
Every year I organize a hands-on cohort course coding BOOTCAMP
to teach you how to build a complex, modern Web Application in
practice (next edition February-March-April-May 2024)
Learn how to start a solopreneur business on the Internet with SOLO LAB (next edition in 2024)