Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I create a dynamic variable name in React?

In React, I am trying to dynamically create my state variable name using a variable and static text. 'level2' will be created by 'level' text plus a variable indicating what level (selectedItem.Level+1).

this.state={
  level1:[""], // city
  level2:[""]  // township
  level3:[""]  // neighborhood 
  level4:[""]  // street
}

When a user clicks on a city, I populate an array of all townships within the city and so on. Through props I know what level was clicked. I would like to dynamically create what state variable to update.

'FilteredListFromClick' is a array of children based on what parent was clicked.

this.setState({level2: FilteredListFromClick}) // hard coding name works, level2 is populated with a list of townships in clicked city.

var levelName = "level" + selectedItem.Level+1; // column1, column2, etc
this.setState({levelName: FilteredListFromClick}) // does not work, state is not updated, results are an empty list 

this.setState({"level"{selectedItem.Level+1}: FilteredListFromClick}) // syntax errors - I've tried playing around with different combos of (), {}, "", and so on. Ideally I would like to set my state in one line like this.
like image 264
Bethany Avatar asked Nov 17 '17 18:11

Bethany


People also ask

How do you define a dynamic variable?

A dynamic variable is a variable you can declare for a StreamBase module that can thereafter be referenced by name in expressions in operators and adapters in that module. In the declaration, you can link each dynamic variable to an input or output stream in the containing module.

How do I create a dynamic list in React?

To render a list dynamically in React, we start by adding a property to the state object. We can populate that property with an array of strings like so. Great. Now we want to move to the render() method to render each list item dynamically.

What is a dynamic variable example?

Dynamic Variable Overview The distinguishing characteristic of a dynamic variable is that its value can change while the application runs. For example, your application might maintain a threshold value that is compared to a field value in each tuple processed.


1 Answers

Use [] brackets like this

this.setState({["level" + (selectedItem.Level+1)]: FilteredListFromClick})
like image 154
Prakash Sharma Avatar answered Sep 20 '22 20:09

Prakash Sharma