Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ReactJS syntax for if else with map function in branch

I'm new to React and struggling with the syntax. I have this block as a div inside my render function. Every change I make goes from one syntax error or another or just doesn't work.

<div className="skillSection">
{        
    if (this.state.challengeChoices.length < 0) {                               
         this.state.challengeChoices.map((para2, i) =>
             <ChallengeSkill key={i} {...para2} callback={this.madeSelection} />)
    }
    else {
        return <div>Hello world</div>
    }   
}   
</div>
like image 747
Danny Ellis Jr. Avatar asked May 22 '26 01:05

Danny Ellis Jr.


2 Answers

Recommend making a function:

renderSkillSection: function(){
    if (this.state.challengeChoices.length < 0) {                               
        return this.state.challengeChoices.map((para2, i) =>
             <ChallengeSkill key={i} {...para2} callback={this.madeSelection} />)
    }
    else {
        return <div>Hello world</div>
    }   
},

render: function(){
  return (<div className="skillSection">
    {this.renderSkillSection()}   
  </div>)
}
like image 93
Blair Anderson Avatar answered May 24 '26 14:05

Blair Anderson


jsx doesn't support conditional statement, but it support ternary operator, so you can do it like this:

<div className="skillSection">
{  this.state.challengeChoices.length < 0 ? (                               
     this.state.challengeChoices.map((para2, i) =>
         <ChallengeSkill key={i} {...para2} callback={this.madeSelection} />)) : ( <div>Hello world</div>)
}  
</div>
like image 26
chenkehxx Avatar answered May 24 '26 15:05

chenkehxx



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!