Reactjs setState() with a dynamic key name?

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?

Solutions/Answers:

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.

Related:  Directive that fires an event when clicking outside of the element

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:

Just wanted to add, that you can also de-structuring to refactor the code and make it look neater.

inputChangeHandler: function ({ target: { id, value }) {
    this.setState({ [id]: value });
},

Solution 5:

In loop with .map work like this:

{
    dataForm.map(({ id, placeholder, type }) => {
        return <Input
            value={this.state.type}
            onChangeText={(text) => this.setState({ [type]: text })}
            placeholder={placeholder}
            key={id} />
    })
}

Note the [] in type parameter.
Hope this helps 🙂

Solution 6:

With ES6+ you can just do [${variable}]