Add/Remove input fields dynamically in React

share link

by Abdul Rawoof A R dot icon Updated: Feb 10, 2023

technology logo
technology logo

Solution Kit Solution Kit  

To make the form with input fields dynamically, we'll create a React state, and this state will have an object. Create an input group and add an input field along with a button i.e the button which is used to delete this input field. Then create a button and on clicking this button we'll dynamically add the input fields.


The main function which is used to add the input fields and remove the input fields is the click() function. It plays a vital role for add and remove the input fields. If we click an "Add" button then a new input field will be added in the DOM. If we want to add one or more input fields then just click again and again the "Add" button to add input fields dynamically. We can add as many as possible input fields according to our needs by just clicking the "Add" button. Also, we can remove those input fields which are added by just clicking the "Remove" button. To add multiple input fields dynamically in React, first, create an array in the state variable then assign a name to the dynamic fields with the help of array indexing like name0, name1.


Steps to Add and Remove Form fields dynamically with React,

  1. Create a form field with input like name and email.
  2. Create add and remove fields by adding functions.
  3. Functional component with complete example.
  4. Class component with complete example.
  5. Then, CSS code.


Here is an example of how you can Add and Remove input fields dynamically in React:

Fig : Preview of the output that you will get on running this code from your IDE.

Code

In this solution we are going to use React library.

import React, { Component } from 'react';

class SocialMedia extends Component {
  constructor() {
    super();
    this.state = {
      name: '',
      SocialData: [],
      socialArray: [
        {
        "id": 1,
        "name": "Website",
        "regex": "(https|http):\\/\\/(www\\.)*"
        },
        {
        "id": 4,
        "name": "Last.fm",
        "regex": "(https|http):\\/\\/www\\.(lastfm\\.com|last\\.fm\\/|lastfm\\.ch).*"
        },
        {
        "id": 5,
        "name": "Facebook",
        "regex": "https:\\/\\/www\\.facebook\\.com\\/.*"
        },
        {
        "id": 6,
        "name": "Twitter",
        "regex": "(https|http):\\/\\/(twitter\\.com).*"
        },
        {
        "id": 8,
        "name": "Instagram",
        "regex": "https:\\/\\/(instagr\\.am\\/.*|instagram\\.com\\/.*)"
        },
        {
        "id": 9,
        "name": "YouTube Channel",
        "regex": "((http|https):\\/\\/|)(www\\.)?youtube\\.com\\/(channel\\/|user\\/)[a-zA-Z0-9]{1,}"
        },
        {
        "id": 11,
        "name": "YouTube Video",
        "regex": "^.*(youtu.be\\/|v\\/|e\\/|u\\/\\w+\\/|embed\\/|v=)([^#\\&\\?]*).*"
        },
        {
        "id": 12,
        "name": "Spotify",
        "regex": "spotify\\:+"
        }
        ]
    };
    this.handleAddSocial = this.handleAddSocial.bind(this);
    this.handleInputValueChange = this.handleInputValueChange.bind(this);
    this.handleRemoveSocial = this.handleRemoveSocial.bind(this);
    this.handleSocialNameChange = this.handleSocialNameChange.bind(this);
    this.selectHandler = this.selectHandler.bind(this);
  }

  handleAddSocial () {
    let array = this.state.SocialData;
    array.push({ id: array.length+1 , socialname: '' })
    this.setState({ SocialData: array})
  }

  handleInputValueChange(e, idx) {
    let nextSocialData = this.state.SocialData.slice();
    nextSocialData[idx].name = e.target.value;
    this.setState({ SocialData: nextSocialData });
  }

  handleSocialNameChange(socialName, idx) {
    let nextSocialData = this.state.SocialData.slice();
    nextSocialData[idx].socialname = socialName;
    this.setState({ SocialData: nextSocialData });
  }

  handleRemoveSocial(idx) {
    let someArray = this.state.SocialData;
    someArray.splice(idx, 1);
    this.setState({ SocialData: someArray });
  }

  render() {
    return (
      <div >
        <button  
          className="newFlyerButton btn mb-4"
          type="button" 
          onClick={this.handleAddSocial}
        >
          <span>
            <img src={plus} alt="plus" className="newFlyerPlus"/>
            <span className="buttonText">ADD NEW</span>
          </span>
        </button>

        <table className="table mt-3 bordered table-hover  white-table addNewSocial">
          <tbody>
            {this.state.SocialData.map((Social, idx) => (
              <tr key={idx} className="row Social">
                <td className="col-6 socialInput">
                  <input
                    type="text"
                    placeholder={`Add New # ${idx+1}`}
                    value={Social.name}
                    onChange={this.handleInputValueChange}
                  />
                </td>
                <td className="col-4 socialSelector">
                  <select
                    onChange={e => {
                      this.handleSocialNameChange(e.target.value, idx);
                    }}
                    value={Social.socialname || "SelectOption"}
                  >
                    <option value="SelectOption" disabled >Select your option</option>
                    { this.state.socialArray.map(socidata =>
                      <option 
                        value={socidata.name} 
                        data={socidata} 
                        key={socidata.id}
                      >
                        {socidata.name}
                      </option>
                    )}
                  </select>
                </td>
                <td className="col-2 closingLink">
                  <i className="fas fa-fw fa-times" onClick={ () => this.handleRemoveSocial(idx) }></i>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    )
  }
}

export default SocialMedia;

Instructions

Follow the steps carefully to get the output easily.

  1. Install the Node.js and React on your IDE(preferable Visual Studio Code).
  2. Create React Application using npx create-react-app foldername.
  3. cd foldername.
  4. Open the folder in IDE.
  5. Copy the code using "copy" button above and paste it into the index.js file(some typos in the above code, we suggest you copy the code from the 'DEMO' given below).
  6. Import ReactDOM in index.js file.
  7. Open the terminal from IDE.
  8. npm start to run the file.


You can also refer to this url 'DEMO' for getting the above output.

I hope you found this useful. I have added the link to dependent libraries, and version information in the following sections.


I found this code snippet by searching for 'how to add remove input fields dynamically in react' in kandi. You can try any such use case!

Environment Tested

I tested this solution in the following versions. Be mindful of changes when working with other versions.

  1. The solution is created in Visual Studio Code 1.73.1.
  2. The solution is tested on node v18.12.1 and npm v8.19.2.
  3. React version-18.2.0.


Using this solution, we are able to add and delete input fields dynamically in React with simple steps. This process also facilities an easy way to use, hassle-free method to create a hands-on working version of code which would help us to add and delete input fields dynamically in React.

Dependent Library

reactby facebook

JavaScript doticonstar image 209050 doticonVersion:v18.2.0doticon
License: Permissive (MIT)

The library for web and native user interfaces

Support
    Quality
      Security
        License
          Reuse

            reactby facebook

            JavaScript doticon star image 209050 doticonVersion:v18.2.0doticon License: Permissive (MIT)

            The library for web and native user interfaces
            Support
              Quality
                Security
                  License
                    Reuse

                      You can also search for any dependent libraries on kandi like 'react'.

                      Support

                      1. For any support on kandi solution kits, please use the chat
                      2. For further learning resources, visit the Open Weaver Community learning page.


                      See similar Kits and Libraries