React, focus an item in React when 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 tr…


This content originally appeared on flaviocopes.com and was authored by flaviocopes.com

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


This content originally appeared on flaviocopes.com and was authored by flaviocopes.com


Print Share Comment Cite Upload Translate Updates
APA

flaviocopes.com | Sciencx (2021-02-03T05:00:00+00:00) React, focus an item in React when added to the DOM. Retrieved from https://www.scien.cx/2021/02/03/react-focus-an-item-in-react-when-added-to-the-dom/

MLA
" » React, focus an item in React when added to the DOM." flaviocopes.com | Sciencx - Wednesday February 3, 2021, https://www.scien.cx/2021/02/03/react-focus-an-item-in-react-when-added-to-the-dom/
HARVARD
flaviocopes.com | Sciencx Wednesday February 3, 2021 » React, focus an item in React when added to the DOM., viewed ,<https://www.scien.cx/2021/02/03/react-focus-an-item-in-react-when-added-to-the-dom/>
VANCOUVER
flaviocopes.com | Sciencx - » React, focus an item in React when added to the DOM. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2021/02/03/react-focus-an-item-in-react-when-added-to-the-dom/
CHICAGO
" » React, focus an item in React when added to the DOM." flaviocopes.com | Sciencx - Accessed . https://www.scien.cx/2021/02/03/react-focus-an-item-in-react-when-added-to-the-dom/
IEEE
" » React, focus an item in React when added to the DOM." flaviocopes.com | Sciencx [Online]. Available: https://www.scien.cx/2021/02/03/react-focus-an-item-in-react-when-added-to-the-dom/. [Accessed: ]
rf:citation
» React, focus an item in React when added to the DOM | flaviocopes.com | Sciencx | https://www.scien.cx/2021/02/03/react-focus-an-item-in-react-when-added-to-the-dom/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.