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?
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 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.
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.
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 }); }
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 }); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With