2

I'm working on a employee form in which education details is a part of form. Education details will be having a set of fields like Degree name, Graduation year, University Name etc. Now we have requirement that we will have a plus(+) and minus(-) buttons to add and remove more education fields. So, how can we achieve this dynamic addition and removing of set of education details fields in reactJs.

Manikanta B
  • 1,083
  • 2
  • 16
  • 30

1 Answers1

1

set a fieldCount or something in your parent state. like this:

constructor(props){
   super(props);
   this.addHandler = this.addHandler.bind(this);
   this.removeHandler = this.removeHandler.bind(this);
}

addHandler(event){
  this.setState({fieldCount: this.state.fieldCount + 1})
}

removeHandler(event){
  this.setState({fieldCount: Math.min(this.state.fieldCount - 1, 1)})
}

render(){
   var childs= [];

   for (var i = 0; i < this.state.fieldCount; i++) {
      childs.push(<ChildComponent />);
   }


  return(
     <div>
          {childs}
          <button onClick={this.addHandler}>Add</button>
          <button onClick={this.removeHandler}>Remove</button>
      </div>
  )

}
Emad Emami
  • 6,089
  • 3
  • 28
  • 38