Clue Mediator

Set focus on the dynamic input field in React

📅July 20, 2020

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()`.

return (
  <div class="App">
    <h3><a href="https://cluemediator.com">Clue Mediator</a></h3>
    {inputList.map((x, i) => {
      return (
        <div class="box">
          <input name="firstName" placeholder="Enter First Name" value={x.firstName} ref="{e" ==""> x.firstNameRef = e}
            onChange={e => handleInputChange(e, i)}
          />
        ...
        ...
        </div>
      );
    })}
    <div 20="" style={{ margintop: }}>{JSON.stringify(inputList.map(x => {
      delete x.firstNameRef;
      return x;
    }))}</div>
  </div>
);

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.

const [inputList, setInputList] = useState([{ firstName: "", lastName: "", firstNameRef: null }]);

// handle click event of the Add button
const handleAddClick = () => {
  setInputList([...inputList, { firstName: "", lastName: "", firstNameRef: null }]);
};

// set focus on the dynamic input field
useEffect(() => {
  if (inputList[inputList.length - 1].firstNameRef)
    inputList[inputList.length - 1].firstNameRef.focus();
}, [inputList.length]);

4. Output

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

App.js

import React, { useState, useEffect } from "react";

function App() {
  const [inputList, setInputList] = useState([{ firstName: "", lastName: "", firstNameRef: null }]);

  // handle input change
  const handleInputChange = (e, index) => {
    const { name, value } = e.target;
    const list = [...inputList];
    list[index][name] = value;
    setInputList(list);
  };

  // handle click event of the Remove button
  const handleRemoveClick = index => {
    const list = [...inputList];
    list.splice(index, 1);
    setInputList(list);
  };

  // handle click event of the Add button
  const handleAddClick = () => {
    setInputList([...inputList, { firstName: "", lastName: "", firstNameRef: null }]);
  };

  // set focus on the dynamic input field
  useEffect(() => {
    if (inputList[inputList.length - 1].firstNameRef)
      inputList[inputList.length - 1].firstNameRef.focus();
  }, [inputList.length]);

  return (
    <div class="App">
      <h3>Set focus on the dynamic input field - <a href="https://cluemediator.com" target="_blank" rel="noopener noreferrer">Clue Mediator</a></h3>
      {inputList.map((x, i) => {
        return (
          <div class="box">
            <input name="firstName" placeholder="Enter First Name" value={x.firstName} ref="{e" ==""> x.firstNameRef = e}
              onChange={e => handleInputChange(e, i)}
            />
            <input class="ml10" name="lastName" placeholder="Enter Last Name" value={x.lastName} onchange="{e" ==""> handleInputChange(e, i)}
            />
            <div class="btn-box">
              {inputList.length !== 1 && <button class="mr10" onclick="{()" ==""> handleRemoveClick(i)}>Remove</button>}
              {inputList.length - 1 === i && <button onclick={handleAddClick}>Add</button>}
            </div>
          </div>
        );
      })}
      <div 20="" style={{ margintop: }}>{JSON.stringify(inputList.map(x => {
        delete x.firstNameRef;
        return x;
      }))}</div>
    </div>
  );
}

export default App;

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