Clue Mediator

Add or remove input fields dynamically with ReactJS

📅February 12, 2020

Today we will show you how to add or remove input fields dynamically with ReactJS. In a real project, sometimes you need to implement the dynamic form fields using React. So you will find the step by step instruction to create dynamic form.

Dynamically Adding Multiple Input Fields in React JS, How to implement a dynamic form with controlled components in React hooks, react native dynamically add input fields to form, add input field on click react, building a dynamic, controlled form with react, dynamically adding multiple input fields react, react add form field dynamically, react-dynamic-forms github, react dynamic form generation, react add component dynamically on click.

Checkout more articles on ReactJS

Here we will take an example, where we will display two input fields dynamically and also add two buttons to add and remove the fields.

https://youtu.be/c9oC5qjIiWY

Steps to implement dynamic input fields

  1. Create react application
  2. Design the form
  3. Implement logic to add/remove fields
  4. Output

1. Create react application

Let’s start by creating a simple react application with the help of the create-react-app. If you don’t know how to create a react application then refer to the link below.

Create React Application

2. Design the form

To design the form, we will add two inputs and two buttons into the form.

import React, { useState } from "react";

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

  return (
    <div className="App">
      <h3><a href="https://cluemediator.com">Clue Mediator</a></h3>
      {inputList.map((x, i) => {
        return (
          <div className="box">
            <input
              name="firstName"
              value={x.firstName}
            />
            <input
              className="ml10"
              name="lastName"
              value={x.lastName}
            />
            <div className="btn-box">
              {inputList.length !== 1 && <button className="mr10">Remove</button>}
              {inputList.length - 1 === i && <button>Add</button>}
            </div>
          </div>
        );
      })}
      <div style={{ marginTop: 20 }}>{JSON.stringify(inputList)}</div>
    </div>
  );
}

export default App;

Our form should look like below.

Design Form - Add or remove input fields dynamically with ReactJS - Clue Mediator

Design Form - Add or remove input fields dynamically with ReactJS - Clue Mediator

3. Implement logic to add/remove fields

Now it's time to write the logic. We will have three methods like input change, add button click and remove button click.

// 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: "" }]);
};
  1. `handleInputChange` - This method can be used on change of the input fields. In this method we need to update the value based on the given index.
  2. `handleRemoveClick` - Here we will remove elements from the list based on the index.
  3. `handleAddClick` - To add the new element in the list we have to call this method.

Let's bind these methods with elements.

return (
  <div className="App">
    <h3><a href="https://cluemediator.com">Clue Mediator</a></h3>
    {inputList.map((x, i) => {
      return (
        <div className="box">
          <input
            name="firstName"
			placeholder="Enter First Name"
            value={x.firstName}
            onChange={e => handleInputChange(e, i)}
          />
          <input
            className="ml10"
            name="lastName"
			placeholder="Enter Last Name"
            value={x.lastName}
            onChange={e => handleInputChange(e, i)}
          />
          <div className="btn-box">
            {inputList.length !== 1 && <button
              className="mr10"
              onClick={() => handleRemoveClick(i)}>Remove</button>}
            {inputList.length - 1 === i && <button onClick={handleAddClick}>Add</button>}
          </div>
        </div>
      );
    })}
    <div style={{ marginTop: 20 }}>{JSON.stringify(inputList)}</div>
  </div>
);

Write the above code together in one file and check the output.

App.js

import React, { useState } from "react";

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

  // 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: "" }]);
  };

  return (
    <div className="App">
      <h3><a href="https://cluemediator.com">Clue Mediator</a></h3>
      {inputList.map((x, i) => {
        return (
          <div className="box">
            <input
              name="firstName"
			  placeholder="Enter First Name"
              value={x.firstName}
              onChange={e => handleInputChange(e, i)}
            />
            <input
              className="ml10"
              name="lastName"
			  placeholder="Enter Last Name"
              value={x.lastName}
              onChange={e => handleInputChange(e, i)}
            />
            <div className="btn-box">
              {inputList.length !== 1 && <button
                className="mr10"
                onClick={() => handleRemoveClick(i)}>Remove</button>}
              {inputList.length - 1 === i && <button onClick={handleAddClick}>Add</button>}
            </div>
          </div>
        );
      })}
      <div style={{ marginTop: 20 }}>{JSON.stringify(inputList)}</div>
    </div>
  );
}

export default App;

4. Output

Output - Add or remove input fields dynamically with ReactJS - Clue Mediator

Output - Add or remove input fields dynamically with ReactJS - Clue Mediator

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

Demo & Source Code

Github Repository StackBlitz Project