Reactjs setState() with a dynamic key name?

JavascriptReactjsComputed Properties

Javascript Problem Overview


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?

Javascript Solutions


Solution 1 - Javascript

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 - Javascript

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 - Javascript

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 - Javascript

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 });
},

Solution 5 - Javascript

I had a similar problem.

I wanted to set the state of where the 2nd level key was stored in a variable.

e.g. this.setState({permissions[perm.code]: e.target.checked})

However this isn't valid syntax.

I used the following code to achieve this:

this.setState({
  permissions: {
    ...this.state.permissions,
    [perm.code]: e.target.checked
  }
});

Solution 6 - Javascript

this.setState({ [`${event.target.id}`]: event.target.value}, () => {
      console.log("State updated: ", JSON.stringify(this.state[event.target.id]));
    });

Please mind the quote character.

Solution 7 - Javascript

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 8 - Javascript

I was looking for a pretty and simple solution and I found this:

this.setState({ [`image${i}`]: image })

Hope this helps

Solution 9 - Javascript

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

Solution 10 - Javascript

when the given element is a object:

handleNewObj = e => {
        const data = e[Object.keys(e)[0]];
        this.setState({
            anykeyofyourstate: {
                ...this.state.anykeyofyourstate,
                [Object.keys(e)[0]]: data
            }
        });
    };

hope it helps someone

Solution 11 - Javascript

Your state with dictionary update some key without losing other value

state = 
{	
    name:"mjpatel"	
    parsedFilter:
    {
      page:2,
      perPage:4,
      totalPages: 50,
    }
}

Solution is below

 let { parsedFilter } = this.state
 this.setState({
      parsedFilter: {
        ...this.state.parsedFilter,
        page: 5
      }
  });

here update value for key "page" with value 5

Solution 12 - Javascript

try this one please.

State is here as example

 this.state = {
            name: '',
            surname: '',
            username: '',
            email: '',
  }

Onchange function is here.

onChangeData = (type, event) => {
    const stateData = this.state;
    if (event === "" || event === "Seçiniz")
        stateData[type] = undefined
    else
        stateData[type] = event

    this.setState({ stateData});
}

Solution 13 - Javascript

Can use a spread syntax, something like this:

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestiontradView Question on Stackoverflow
Solution 1 - JavascripttradView Answer on Stackoverflow
Solution 2 - Javascriptvikram jeet singhView Answer on Stackoverflow
Solution 3 - JavascriptsintaxiView Answer on Stackoverflow
Solution 4 - JavascriptsaulableView Answer on Stackoverflow
Solution 5 - JavascriptMatthew HoltomView Answer on Stackoverflow
Solution 6 - JavascriptjavatarView Answer on Stackoverflow
Solution 7 - JavascriptJohnatan MacielView Answer on Stackoverflow
Solution 8 - JavascriptCatalinaView Answer on Stackoverflow
Solution 9 - JavascriptJujhar SinghView Answer on Stackoverflow
Solution 10 - JavascriptReinaldo EPView Answer on Stackoverflow
Solution 11 - Javascriptmanoj patelView Answer on Stackoverflow
Solution 12 - JavascriptHacı Celal AygarView Answer on Stackoverflow
Solution 13 - JavascriptstaView Answer on Stackoverflow