Problem
EDIT: This is a copy of this post, which can be found here.
I can’t find any examples of setting the state using a dynamic key name. This is what I’d like to accomplish:
inputChangeHandler : function (event) {
this.setState( { event.target.id : event.target.value } );
},
where the state key to be modified is event.target.id Is there no way to do this in React?
Asked by trad
Solution #1
I utilized this as a result of @Cory’s suggestion:
inputChangeHandler : function (event) {
var stateObject = function() {
returnObj = {};
returnObj[this.target.id] = this.target.value;
return returnObj;
}.bind(event)();
this.setState( stateObject );
},
You can do this with calculated property names if you’re using ES6 or the Babel transpiler to translate your JSX code:
inputChangeHandler : function (event) {
this.setState({ [event.target.id]: event.target.value });
// alternatively using template strings for strings
// this.setState({ [`key${event.target.id}`]: event.target.value });
}
Answered by trad
Solution #2
When dealing with many controlled input elements, you can give each one a name attribute and allow the handler function decide what to do based on the value of event.target.name.
For example:
Answered by vikram jeet singh
Solution #3
This is how I did it…
inputChangeHandler: function(event) {
var key = event.target.id
var val = event.target.value
var obj = {}
obj[key] = val
this.setState(obj)
},
Answered by sintaxi
Solution #4
I simply wanted to add that de-structuring can also be used to modify the code and make it appear cleaner.
inputChangeHandler: function ({ target: { id, value }) {
this.setState({ [id]: value });
},
Answered by saulable
Solution #5
I had a problem that was comparable to yours.
I needed to change the status of a variable that held the 2nd level key.
e.g. this.setState({permissions[perm.code]: e.target.checked})
This, however, isn’t correct syntax.
To accomplish this, I used the following code:
this.setState({
permissions: {
...this.state.permissions,
[perm.code]: e.target.checked
}
});
Answered by Matthew Holtom
Post is based on https://stackoverflow.com/questions/29280445/reactjs-setstate-with-a-dynamic-key-name