Set focus on the dynamic input field in React

Today we’ll show you how to set focus on the dynamic input field in React after rendering. Here we will use an existing example and continue on it.

As per the request of our readers, we decided to provide the solution to their query for implementation of the auto focus on the dynamic input field in ReactJS.

Let’s continue with our previous article Add or remove input fields dynamically with ReactJS and enhance the functionality to set auto focus.

Steps to set auto focus on the input field after render

  1. Implement demo to add or remove input fields dynamically
  2. Manage an input reference in the state variable
  3. Set the focus on the dynamic input field
  4. Output

1. Implement demo to add or remove input fields dynamically

First, create a demo to add or remove input fields dynamically in React. Use the following article for more information.

Add or remove input fields dynamically with ReactJS

2. Manage an input reference in the state variable

Now, let’s assume that we need to set the focus on the firstName when we add/remove input dynamically.

For that, we have to take the one more variable in the inputList for an input reference. Also delete that variable to avoid the error while displaying on the page using JSON.stringify().

3. Set the focus on the dynamic input field

In the next step, we have to set the focus on the dynamic input field also we are adding one more variable firstNameRef in state object for an input reference. Check out the below code.

4. Output

Let’s combine all code together and see how it looks.

App.js

Output - Set focus on the dynamic input field in React - Clue Mediator
Output – Set focus on the dynamic input field in React – Clue Mediator

That’s it for today.
Thank you for reading. Happy Coding..!!

Demo & Source Code

Github Repository StackBlitz Project
If you found value in this article,
you can support us by buying me a coffee! ☕

You may also like...

2 Responses

  1. Dinesh says:

    Thanks much.. I have query might be a basic one..so, is it not necessary to use a createRef to be used as ref in Input component.? Thanks.

Leave a Reply

Your email address will not be published. Required fields are marked *