简体   繁体   中英

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>

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>)
}

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>

I like the following approach when it's just an if statement:

<div className="skillSection">
    {this.state.challengeChoices.length < 0 && 
        <ChallengeSkill key={i} {...para2} callback={this.madeSelection} />
    }
</div>

Of course, if/else has many options:

// Use inline if/else with some more readable spacing/indentation
render() {
    return (
        <div className="skillSection">
            {this.state.challengeChoices.length < 0 ? (
                <ChallengeSkill key={i} {...para2} callback={this.madeSelection} />
            ) : (
                <div>False</div>
            )}
        </div>
    )
}

// Define as variable
render() {
    let dom = <div>False</div>;
    if (this.state.challengeChoices.length < 0) {
        dom = <ChallengeSkill key={i} {...para2} callback={this.madeSelection} />;
    }

    return (
        <div className="skillSection">
            {dom}
        </div>
    )
}

// Use another method
getDom() {
    if (this.state.challengeChoices.length < 0) {
        return <ChallengeSkill key={i} {...para2} callback={this.madeSelection} />;
    }

    return <div>False</div>;
}

render() {
    return (
        <div className="skillSection">
            {this.getDom()}
        </div>
    )
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM