Reputation: 19
I have elements that are editable and the code I have right now is pretty long and probably just unnecessary, so how can I make this just shorter and cleaner?
handleChange(e) {
console.log(e.target.id)
if (e.target.id === "name") {
this.setState({
name: e.target.value
})
} else if (e.target.id === "address") {
this.setState({
address: e.target.value
})
} else if (e.target.id === "phone") {
this.setState({
phone: e.target.value
})
} else if (e.target.id === "email") {
this.setState({
email: e.target.value
})
}
}
```
Upvotes: 0
Views: 18
Reputation: 53874
If your target.id
matching the state key (as it seems from your example), you can use Property accessors:
const targetId = e.target.id;
if (this.state[targetId]) { // check if id exists
this.setState({ [e.target.id]: e.target.value });
} else { // default case
// fill
}
Upvotes: 1