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.
-
check my answer belowEmad Emami– Emad Emami2017-10-30 04:00:14 +00:00Commented 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.Manikanta B– Manikanta B2017-10-30 06:37:49 +00:00Commented Oct 30, 2017 at 6:37
Add a comment
|
1 Answer
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>
)
}