I have rendered a component that has select dropdowns multiple times on a button click event.
class AppComponent extends React.Component {
constructor(props){
super(props);
this.state = {
numChildren: 0
}
this.onAddChild = this.onAddChild.bind(this);
}
render () {
const children = [];
for (var i = 0; i < this.state.numChildren; i += 1) {
children.push(<ChildComponent key={i} number={i} />);
};
return (
<ParentComponent addChild={this.onAddChild} submit={this.submitData}>
{children}
</ParentComponent>
);
}
submitData(){
console.log("Submit Data button");
}
onAddChild() {
this.setState({
numChildren: this.state.numChildren + 1
});
}
}
ParentComponent is adding childcomponent on onClick event.
const ParentComponent = props => (
<div className="card calculator">
<button onClick={props.addChild}>Add Another Child
Component</button>
<button onClick={props.submit}>Submit Data</button>
{props.children}
</div>
);
const ChildComponent = props => < NewComponent />;
class NewComponent extends React.Component{
constructor(props){
super(props);
this.state = {
first: null,
second: null,
third : null,
}
this.changeFirst = this.changeFirst.bind(this);
this.changeSecond = this.changeSecond.bind(this);
this.changeThird = this.changeThird.bind(this);
}
changeFirst(e) {
this.setState({
first : e.target.value
});
}
changeSecond(e) {
this.setState({
second : e.target.value
});
}
changeThird(e) {
this.setState({
third : e.target.value
});
}
render (){
return (
<div>
<select onChange={this.changeFirst}>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
<option value = "Mahindra"> Mahindra</option>
<option value = "Car"> Car</option>
</select>
<select onChange={this.changeSecond}>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
<option value = "Mahindra"> Mahindra</option>
<option value = "Car"> Car</option>
</select>
<select onChange={this.changeThird}>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
<option value = "Mahindra"> Mahindra</option>
<option value = "Car"> Car</option>
</select>
</div>
);
}
}
NewComponent is getting rendered as childcomponent when button is clicked. I have added changeFirst, changeSecond and changeThird custom functions to handle change event and set state of NewComponent (child component).
What I want to do is, I want to get list of all selected values of each child component instance. Any help is appreciated.