Coder Perfect

Reactjs setState() with a dynamic key name?


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

where the state key to be modified is 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[] =;
         return returnObj;

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

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

For example:

Answered by vikram jeet singh

Solution #3

This is how I did it…

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

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]:})

This, however, isn’t correct syntax.

To accomplish this, I used the following code:

  permissions: {

Answered by Matthew Holtom

Post is based on