Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get state value by a dynamic key in react

Let's say in my component I set the state like so:

this.setState({
      test: "value",
      othertest: "value"        
});

If, elsewhere in my code, I have an array containing the keys for these values, ie- keys = ["test", "othertest"] how can I loop through this array to find the value of the corresponding state value?

like image 873
Snailer Avatar asked May 15 '17 17:05

Snailer


People also ask

How do you get a state value 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.

How do you set a state dynamically 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.


1 Answers

State is an object, so you can access any value by:

this.state[key]

Use any loop map, forEach etc to iterate the array and access the value by this.state[key], like this:

a.forEach(el => console.log(this.state[el]))

Check this snippet:

let state = {a: 1, b: 2};
let arr = ['a', 'b'];

let values = arr.map(el => state[el])

console.log(values);
like image 79
Mayank Shukla Avatar answered Sep 22 '22 02:09

Mayank Shukla