How to Dynamically Add Input Fields on Button Click in ReactJs
Tags: frontend, react, javascript, tutorial
Published: 2023-09-12 14:17:01

This article focuses on the topic of dynamically adding and removing input fields with a button click. This feature allows users to add more input fields as needed, enhancing the flexibility and usability of forms and data collection processes. This tutorial will guide you on how to successfully add and remove dynamic input fields from your applications.

We will be displaying two input fields and also adding two buttons to dynamically add or delete the fields.

## **Create A React Component**
Let's start by creating a react component that will contain the input fields. You can create a new component or edit an existing one by adding the following code.

``` 
import { useState } from "react";

export default function AddDynamicInputFields() {
  const [inputs, setInputs] = useState([{ firstName: "", lastName: "" }]);

  const handleAddInput = () => {
    setInputs([...inputs, { firstName: "", lastName: "" }]);
  };

  const handleChange = (event, index) => {
    let { name, value } = event.target;
    let onChangeValue = [...inputs];
    onChangeValue[index][name] = value;
    setInputs(onChangeValue);
  };

  const handleDeleteInput = (index) => {
    const newArray = [...inputs];
    newArray.splice(index, 1);
    setInputs(newArray);
  };


  return (
    <div className="container">
      {inputs.map((item, index) => (
        <div className="input_container" key={index}>
          <input
            name="firstName"
            type="text"
            value={item.firstName}
            onChange={(event) => handleChange(event, index)}
          />
          <input
            name="lastName"
            type="text"
            value={item.lastName}
            onChange={(event) => handleChange(event, index)}
          />
          {inputs.length > 1 && (
            <button onClick={() => handleDeleteInput(index)}>Delete</button>
          )}
          {index === inputs.length - 1 && (
            <button onClick={() => handleAddInput()}>Add</button>
          )}
        </div>
      ))}

      <div className="body"> {JSON.stringify(inputs)} </div>
    </div>
  );
}

```

First, we initialized the `inputs` state variable as an array containing an object that has “firstName” and “lastName” properties, both initially set to an empty string. We would be using this state to update and manage our input field values.

We used the `setInputs` function to update the inputs state variable. `...inputs` we used the spread operator to make a shallow copy of the inputs array, which creates a new array with the same values as the previous ones.

The `handleChange` function is used to update the value of a specific input field in an array of input fields based on the user’s input. It makes use of the `name` and `value` properties of the event object to identify which input fields to update and what values to assign to them.  This function takes in two parameters;
- Event :  an event object that is triggered by a change in the input fields.
- Index: An index value that represents the position of the input field in an array of input fields.

The `handleDeleteInput` function receives one parameter `index`, which represents the index of the input field to be deleted from a copy of the `inputs` array. Afterwards, it updates the state with the modified array.

We use the map function to iterate over the `inputs` array and render elements for each input field and its associated buttons.  For each item in the inputs array, we create a `<div className="input_container">` element containing two input fields for firstName and lastName.

```
 {inputs.length > 1 && (
   <button onClick={() => handleDeleteInput(index)}>Delete</button>
 )}
```
The conditional rendering from the code block above checks if the `inputs` array contains more than one input field; if it does, it displays the delete button.

```
{index === inputs.length - 1 && (
    <button onClick={() => handleAddInput()}>Add</button>
)}
```
From the code block above, the conditional rendering checks if the current “index” matches the last input field in the “inputs” array, and if it does, it displays the “add” button.



## Render The Component
Next, we can render the component we created earlier, AddDynamicInputFields, in our main application file (App.js).

```
import AddDynamicInputFields from "./AddInputFields";
import "./styles.css";

export default function App() {
  return (
    <div className="App">
      <h1>Dynamically add input fields</h1>
      <AddDynamicInputFields />
    </div>
  );
}

```



## Styling
Your input fields and buttons can be styled using CSS or a UI framework like Tailwind CSS. Feel free to modify your styling to fit your application’s designs.



## Test Your Application
Thats it! You can use “npm start” or your preferred way to start your React application. Now you can add and delete input fields dynamically.

You can find the tutorial repo in this [codesandbox](https://codesandbox.io/s/how-to-dynamically-add-input-fields-by-button-clicl-3jqtww)

Please let me know if this post was helpful by leaving a comment or reaction.

Thank you!