Reputation: 784
I have a function in a react app that uses setState
...
handleChange: (e, id) => {
e.preventDefault()
setState({ id: e.target.value })
}
...
The thing is the id
is just a placeholder for the fields in the state object but everytime the function is triggered it creates a new field id
and assigns the last updated value in the form.
I'm probably doing it wrong so I was wondering if there's a work around or solution to this.
Any help would be appreciated.
Upvotes: 1
Views: 2374
Reputation: 104379
Since id is a variable that is having the state key value, so you need to use []
, what it will happen is, the id will get replaced by it's value.
If you don't use []
then id will be treated as a "id" string.
Like this:
handleChange: (e, id) => {
e.preventDefault()
this.setState({ [id]: e.target.value })
}
Upvotes: 3