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( { : } );

where 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[] =;
         return returnObj;

    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({ []: });
    // alternatively using template strings for strings
    // this.setState({ [`key${}`]: });

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

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

For example:

inputChangeHandler(event) {
  this.setState({ []: });

Solution 3:

How I accomplished this…

inputChangeHandler: function(event) {
  var key =
  var val =
  var obj  = {}
  obj[key] = val

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:

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

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

Solution 6:

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