Search code examples
reactjsconditional-rendering

How to define an object inside the render part?


In my render code I create a map in order to use it with the conditional rendering of React but I get an undefined error because it can't find it. Is it a way to fix that ?

render(){
    if(this.state.jsondata.prediction2){
        const occurrenceMap2 = Object.values(this.state.jsondata.prediction2).reduce((finalMap, item) => {
            finalMap[item] = ++finalMap[item] || 1;   
            return finalMap;
        } , {})
    }
...

   {this.state.jsondata.prediction2 &&
     <p> occurrenceMap2[0] </p>
   }
}


Solution

  • Remove the if statement and declare occurrenceMap2 once and set a default value if this.state.jsondata.prediction2 doesn't a have a value.

    const occurrenceMap2 = this.state.jsondata.prediction2 && Object.values(this.state.jsondata.prediction2).reduce((finalMap, item) => {
      finalMap[item] = ++finalMap[item] || 1;   
      return finalMap;
    } , {}) || []; // set a default value here