Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 708
trad Avatar asked Mar 26 '15 14:03

trad


People also ask

How do I set a dynamic state in React?

Step 1: Create a react application by typing the following command in the terminal. Step 2: Now, go to the project folder i.e project_name by running the following command. Example: Let us create an input field that takes the state name as input and state value as another input.

Why is setState () in React async instead of sync?

Why setState() is async? ReactJs sets its state asynchronously because it can result in an expensive operation. Making it synchronous might leave the browser unresponsive. Asynchronous setState calls are batched to provide a better user experience and performance.

What is the difference between setState () and replaceState () methods?

When you use setState() the current and previous states are merged. replaceState() throws out the current state, and replaces it with only what you provide. Usually setState() is used unless you really need to remove all previous keys for some reason.


2 Answers

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 }); } 
like image 143
trad Avatar answered Sep 20 '22 11:09

trad


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 });  }
like image 27
vikram jeet singh Avatar answered Sep 20 '22 11:09

vikram jeet singh