kandi background
Explore Kits

Add Form Fields Dynamically in ReactJs

by Abdul Rawoof A R Updated: Jan 24, 2023

In this kit we are going to see how to add form fields dynamically in ReactJs with simple steps. If you want to dynamically add elements, you should have a container where to place them. For instance, a <div id="container"> . Let's add the function to the button via an onClick event. Now, in the addFields function, we need to create an object. And every time we click the button, it will be pushed to the inputFields state, thus creating a new input field. Then set this newField inside the inputFields state. To add form fields dynamically use this ready-made code snippet solution on kandi to perform the task. Just copy the code snippet and pate it in your IDE.

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.

JavaScriptLines of Code : 126License : CC BY-SA 4.0

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 star image 201115 Version:18.2.0

License: Permissive (MIT)

A declarative, efficient, and flexible JavaScript library for building user interfaces.

Support
Quality
Security
License
Reuse

reactby facebook

JavaScript star image 201115 Version:18.2.0 License: Permissive (MIT)

A declarative, efficient, and flexible JavaScript library for building user interfaces.
Support
Quality
Security
License
Reuse

reactstrapby reactstrap

JavaScript star image 10445 Version:6.4.0

License: Permissive (MIT)

Simple React Bootstrap 5 components

Support
Quality
Security
License
Reuse

reactstrapby reactstrap

JavaScript star image 10445 Version:6.4.0 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

JavaScript
Frontend Framework
User Interface