Reactjs setState() with a dynamic key name?
EDIT: this is a duplicate, see here
I can't find any examples of using a dynamic key name when setting the state. This is what I want to do:
inputChangeHandler : function (event) {
this.setState( { event.target.id : event.target.value } );
},
where event.target.id is used as the state key to be updated. Is this not possible in React?
Solution 1:
Thanks to @Cory's hint, i used this:
inputChangeHandler : function (event) {
var stateObject = function() {
returnObj = {};
returnObj[this.target.id] = this.target.value;
return returnObj;
}.bind(event)();
this.setState( stateObject );
},
If using ES6 or the Babel transpiler to transform your JSX code, you can accomplish this with computed property names, too:
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 });
}
Solution 2:
When you need to handle multiple controlled input elements, you can add a name attribute to each element and let the handler function choose what to do based on the value of event.target.name.
For example:
inputChangeHandler(event) {
this.setState({ [event.target.name]: event.target.value });
}
Solution 3:
How I accomplished this...
inputChangeHandler: function(event) {
var key = event.target.id
var val = event.target.value
var obj = {}
obj[key] = val
this.setState(obj)
},
Solution 4:
I just wanted to add, that you can also use de-structuring to refactor the code and make it look neater.
inputChangeHandler: function ({ target: { id, value }) {
this.setState({ [id]: value });
},