I am trying to create an immutable state array that is dynamically populated by inputs. However, i am unable to create new state and add it to my people array. What is the correct way to do this? Below is a link to a jsfiddle demo of the problem.
LINK TO DEMO: http://jsfiddle.net/560fyjnp/1536/
Mapping and returning appended array:
appendPerson() {
let newPerson = {
name: '',
age: '',
school: ''
};
this.setState((prevState) => ({
people: prevState.people.concat([newPerson])
}));
}
Handling changes from the inputs:
handleChange(e) {
this.setState({[e.target.name]: e.target.value})
}
Example Input:
Name: <input name="name" value={person.name} onChange={this.props.handleChange} />
Mapping Over the state and showing the stateful strings:
{this.state.people.map((person, index) =>
<div key={index}>
Name: {person.name}<br />
Age: {person.age}<br />
School: {person.school}
<hr/>
</div>
)}
handleChangewill not work because you aren't specifying an index in yourpeoplearray to update. All your passing is{name: 'name'}, but how does your code know which person it should update?