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.
Asked
Active
Viewed 863 times
2
-
check my answer below – Emad Emami Oct 30 '17 at 04: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. – Manikanta B Oct 30 '17 at 06:37
1 Answers
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