Reputation: 694
Iam creating a react app in which i want to render a component on every button click.But i could do it only once.
class AddForm extends React.Component{
constructor(props){
super(props);
this.state={
anotherForm:false,
}
this.newForm=this.newForm.bind(this);
}
newForm(){
this.setState({
anotherForm:true
})
}
render(){
return(
<div>
<button onClick={this.newForm}>AddForm</button>
<EducationDetails/>
{this.state.anotherForm?<EducationDetails/>:null}
</div>
)
}
}
Here the component EducationDetails
is to be rendered whenever the AddForm button is clicked.But i couldn't figure it out.
Upvotes: 2
Views: 2466
Reputation: 1581
Here is a working jsfiddle
Lets assume this is your Education Details Component.
class EducationDetails extends React.Component {
constructor(props) {
super(props);
}
render() {
return (<div>
<p>FirstName: <input type="text" value={this.props.value || ''} /></p>
<p>LastName: <input type="text" value={this.props.value || ''} /></p>
</div>
);
}
}
In your AddForm component, You could have a count and whenever you click add more button increment your count and display Education detail form based on your count state.
class AddForm extends React.Component {
constructor(props) {
super(props);
this.state = {value: [], count: 1}; //initial you'll have one form
}
addMore(){
this.setState({count: this.state.count+1})//on click add more forms
}
displayForm(){
let forms = [];
for(let i = 0; i < this.state.count; i++){
forms.push(
<div key={i}>
<EducationDetails value={this.state.value[i] || ''} />
</div>
)
}
return forms || null;
}
render() {
return (
<form >
{this.displayForm()}
<input type='button' value='add more' onClick={this.addMore.bind(this)}/>
</form>
);
}
}
ReactDOM.render(<AddForm />, document.getElementById('container'));
You could also remove the form using the same concept decrement your count something like
removeClick(){
this.setState({count: this.state.count - 1})
}
And just under your add more button, add another button to remove
<input type='button' value='remove' onClick={this.removeClick.bind(this)}/>
Upvotes: 4