Search code examples
reactjssyntaxjsx

Variable inside JS expression in React


This is my React code:

const colors = ["RED", "BLUE", "GREEN", "YELLOW"];

// in class component 

constructor(props) {
  super(props);

  // these are filled in somewhere else in the code, but not shown here
  this.state = {
    redFiles: [],
    blueFiles: [],
    greenFiles: [],
    yellowFiles: []
  }
}
//somewhere else in the code:

render() {
  <div>
    {colors.map( color => 
      {this.state._____Files.length}      // problem area: how do I put color.toLowerCase() variable within that blank 
  </div>
}

In the indicated "problem area", how do I put the color.toLowerCase() variable in that blank such that we have this.state.redFiles.length, this.state.blueFiles.length, this.state.greenFiles.length, and this.state.yellowFiles.length?


Solution

  • You can try with this

    {colors.map(color => (
          <div key={color}>
            {this.state[color.toLowerCase() + "Files"].length}
          </div>
        ))}