Add Form Fields Dynamically in ReactJs

share link

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

technology logo
technology logo

Solution Kit Solution Kit  

Dynamic Forms are nothing but one of the crucial parts of a web app. It plays a vital role in collecting data or information about the users. Developers are responsible to validate those input data in the form fields in order to provide a good user experience.


There are two types of forms inputs in React,

  • Uncontrolled Component
  • Controlled Component


To add multiple input fields dynamically in JavaScript,

  • Creating a copy of a field group to be used as a template.
  • Getting the container of the input fields.
  • Set input fields id is based on the total number of form groups in the parent.
  • addinput() - make sure this method adds to the button.
  • At the end insert the input form before the end of the parent form.


The main purpose of the forms is to collect the required information or data in a meaningful fashion and logically for communication and pass to another entity. It is advisable to have a JavaScript function that handles the form submission and also has access to the form's user data. The traditional way to do this technique is called 'controlled components'. The benefits of forms are increased efficiency of employees and reduced volume of work. Instead of manually putting the data into the databases, we can automate the process by directing the data from the forms to the databases.


Here is an example of how you can add form fields dynamically in ReactJS:

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

Code

In this solution we're using React and Reactstrap libraries.

import React, { Component } from 'react';
import { render } from 'react-dom';
import { Form, FormGroup, Label, Progress,Button } from 'reactstrap';
import Hello from './Hello';
import './style.css';


const byPropKey = (propertyName, value) => () => ({
    [propertyName]: value,
  });
class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      name: 'React',
      Information:'',
      ImageUrl:'',
      isUploading: false,
      isUploaded: true,
      showProgress: false,
      progress: 0,
      avatarUrl:'',
      ref:'WhitePapersItems',
      formValid: false,
      content: [{Heading: "", Content: [{value:""}]}]
    };

        this.AddContentBox = this.AddContentBox.bind(this);
        this.AddContentInput = this.AddContentInput.bind(this);
        //this.addContentTextBox = this.addContentTextBox.bind(this);
  }

  AddContentInputFields(element) {
    return element.Content.map(content => {
      return (
        <FormGroup>
          <Label className="set-label-pos upload-img" for="Heading">Content</Label>
          <input className="form-control" type="text"/>
        </FormGroup>
      );
    })
  }

  AddContentBox(){
        return this.state.content.map((element,i)=>(
            <div className="header-content" key={i} >
                <div className="heading-content-wrapper">
                <FormGroup>
                <Label className="set-label-pos upload-img" for="Heading">Heading</Label>
                <input className="form-control" type="text"/>
                </FormGroup>
                { this.AddContentInputFields(element) }
                <FormGroup>
                <Button color="success" onClick={this.AddContentInput.bind(this,i)}>+ Add Content</Button>
                </FormGroup>
            </div>
            </div>
        ))
    }

    handleChange(i, e) {
    const { Heading, value } = e.target;
      let content = [...this.state.content];
      content[i] = {...content[i], [Heading]: value};
      this.setState({ content });
   }

   AddContentInput(index, val){
        console.log('Add ContentInput triggered',val,index);       
        const contents = _.cloneDeep(this.state.content);
        contents[index].Content.push({value:''});

        const item = contents[index].Content;
        console.log('item', item);
        this.setState({content:contents});
        //this.addContentTextBox(item);

    }

    // addContentTextBox(item){
    //   return item.map((element, i)=>(
    //         <FormGroup>
    //            <Label className="set-label-pos upload-img" for="Heading">Content</Label>
    //            <input className="form-control" type="text"/>
    //        </FormGroup>
    //    ));
    // }

     addHeading(event){
        event.preventDefault();
        this.setState(prevState => ({ 
            content: [...prevState.content, { Heading: "", Content: [{value:""}] }]
        }))
        this.AddContentBox();
   }

  render() {
    return (
      <div>


        <Form onSubmit={this.onSubmit}>

                <FormGroup>
                    <Label className="set-label-pos upload-img" for="Information">Information</Label>
                    <textarea className="form-control" rows="10" onChange={event => this.setState(byPropKey('Information', event.target.value))}
                        type="text"/>
                </FormGroup>
                {this.AddContentBox()}
                <div className="add-heading-button">
                    <Button color="primary" onClick={this.addHeading.bind(this)}>+ Add Heading</Button>
                </div>
                <FormGroup>
                <input type="hidden" value={this.state.ImageUrl} onChange={event => this.setState(byPropKey('ImageUrl', event.target.value))}/>
                </FormGroup>

                <Button className="btn btn-danger" size="lg" type="submit">+ Add White Papers Item</Button>
                </Form>

      </div>
    );
  }
}

render(<App />, document.getElementById('root'));

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. Install npm i reactstrap.
  5. Open the folder in IDE.
  6. Copy the code using "copy" button above and paste it in index.js file(remove the earlier code from index.js).
  7. Open the terminal from IDE.
  8. npm start to run the file.


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


I found this code snippet by searching for 'how to add form fields dynamically in reactjs' 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.
  4. Reactstrap version-9.0.2.


Using this solution, we are able to add form fields dynamically in reactjs 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 form fields dynamically in reactjs.

Dependent Libraries

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

                      reactstrapby reactstrap

                      JavaScript doticonstar image 10504 doticonVersion:v9.1.10doticon
                      License: Permissive (MIT)

                      Simple React Bootstrap 5 components

                      Support
                        Quality
                          Security
                            License
                              Reuse

                                reactstrapby reactstrap

                                JavaScript doticon star image 10504 doticonVersion:v9.1.10doticon License: Permissive (MIT)

                                Simple React Bootstrap 5 components
                                Support
                                  Quality
                                    Security
                                      License
                                        Reuse

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

                                          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