9

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.

3 Answers 3

12

Use [] brackets like this

this.setState({["level" + (selectedItem.Level+1)]: FilteredListFromClick})
Sign up to request clarification or add additional context in comments.

2 Comments

How can i call it dynamically then? this.state.["level" + (selectedItem.Level+1)] how can it work like this?
@ShadyHakim You can call it dynamically like this.state["level" + (selectedItem.Level+1)]
3

Prakash's solution works given an advanced enough EcmaScript version.

An older-style and (IMHO) slightly more readable solution is to build the map outside and pass it in.

const newState = {}
newState["level" + selectedItem.Level+1] = FilteredListFromClick
this.setState(newState)

1 Comment

Thank you for the quick reply Robert! I went with Prakash's answer to use fewer lines of code. I'm using the latest EcmaScript version.
0

An small tweak update this answer to a more current approach:

this.setState({
    [`level${selectedItem.Level + 1}`]: FilteredListFromClick
})

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.