Code
........
........
state = {
users: [],
currentUser: '',
currentAge: '',
};
........
........
onSubmitHandler = (e) => {
const Person = {
name: this.state.currentUser, //already assign in another function
age: this.state.currentAge,//already assign in another function
};
this.setState({
users: [...this.state.users, Person],
});
};
render() {
return (
<div>
<h1></h1>
<form onSubmit={this.onSubmitHandler}>
<label>
Enter your name:
<input type="text" onChange={this.onChangeNameHandler} />
</label>
<br />
<label>
Enter your Age:
<input type="number" onChange={this.onChangeAgeHandler} />
</label>
<br />
<input type="submit" />
</form>
<ul>
{this.state.users.map((user) => {
return <UserCard name={user.name} age={user.age} />;
})}
</ul>
</div>
);
}
}
Error
Warning: Each child in a list should have a unique "key" prop.
Check the render method of `UserForm`. See https://reactjs.org/link/warning-keys for more information.
at UserCard (https://react-3agtbk.stackblitz.io/~/src/components/UserCard.js:7:1)
at UserForm (https://react-3agtbk.stackblitz.io/~/src/components/UserForm.js:10:9)
at div
at App
I'm trying to add the Person Object to the users array. However, when I try to console.log(this.state.users), It always shows [ ]. I did add preventDefault in my onSubmitHandler function which solve the issue. In my another project, I did not add onSubmitHandler which still works. Why it happening ? Thanks in advance.