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.

2
  • check my answer below Commented Oct 30, 2017 at 4:00
  • @caesay that is working but the problem is on every change of the input value createUI method is getting executed that should not be the case. Commented Oct 30, 2017 at 6:37

1 Answer 1

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>
  )

}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.