Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get react state with dynamic key [duplicate]

I already know how to setState with a dynamic key name but how do I set a value as the state with a dynamic key?

Example

function thing(key) {
 let stuff = this.state.key;

 //Do stuff
}
like image 341
Aaron Avatar asked Sep 02 '17 17:09

Aaron


People also ask

How do you set a state with a dynamic key name in React?

Output: Open your browser. It will by default open a tab with localhost running and you can see the output shown in the image. Fill in the required details and click on the button. As you can see in the output new state with a dynamic name is created with the value you entered.

Can you set state twice React?

React will call that function with state and props, and use the result for next state. It is safe to call setState with a function multiple times. Updates will be queued and later executed in the order they were called.

What is the use of StrictMode in React?

StrictMode is a tool for highlighting potential problems in an application. Like Fragment , StrictMode does not render any visible UI. It activates additional checks and warnings for its descendants.

How do you get state values in React?

The state and props in React are always in an object format. This means that the value could be accessed from the state and props via key-value pair. To access the normal state object, you can use the key name from the object. The state object will look as shown below.


1 Answers

Didn't even think of think of this as first but all I did was

function thing(key) {
 let stuff = this.state[key];

 //Do stuff
}

and it worked!

like image 94
Aaron Avatar answered Oct 07 '22 01:10

Aaron