Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
60
rated 0 times [  63] [ 3]  / answers: 1 / hits: 23717  / 6 Years ago, wed, april 11, 2018, 12:00:00

I'm currently doing this to conditionally render certain Components:



render() {
return (
<React.Fragment>
<div id=call_notes_app className=row>
<NavTree onNavChange={this.changeActiveGroup} />
{this.state.shownGroup == 1 && <DiscoveryGroup/>}
{this.state.shownGroup == 2 && <FinancialGroup/>}
{this.state.shownGroup == 3 && <SalesStuffGroup/>}
</div>
</React.Fragment>
);
}


When I try to use a switch statement, it doesn't work (I get ERROR ABORT in the console):



render() {
return (
<React.Fragment>
<div id=call_notes_app className=row>
<NavTree onNavChange={this.changeActiveGroup} />

{
switch(this.state.shownGroup) {
case 1:
<DiscoveryGroup/>
break;
case 2:
<FinancialGroup />
break;
default:
<SalesStuffGroup />
}
}
</div>
</React.Fragment>
);
}


Is there a way to do this using switch?


More From » reactjs

 Answers
52

{} is for a single statement. A cleaner way would be switching before the return statement:



render() {
let component = null;
switch(this.state.shownGroup) {
case 1:
component = <DiscoveryGroup />;
break;
case 2:
component = <FinancialGroup />;
break;
default:
component = <SalesStuffGroup />;
}

return (
<React.Fragment>
<div id=call_notes_app className=row>
<NavTree onNavChange={this.changeActiveGroup} />
{component}
</div>
</React.Fragment>
);
}


If you eventually have many dynamic components, splitting things out to seperate methods cleans things up even more:



renderGroup(group) {
switch (group) {
case 1:
return <DiscoveryGroup />;
case 2:
return <FinancialGroup />;
default:
return <SalesStuffGroup />;
}
}

render() {
return (
<React.Fragment>
<div id=call_notes_app className=row>
<NavTree onNavChange={this.changeActiveGroup} />
{this.renderGroup(this.state.shownGroup)}
</div>
</React.Fragment>
);
}

[#54693] Monday, April 9, 2018, 6 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
mikael

Total Points: 73
Total Questions: 115
Total Answers: 86

Location: Central African Republic
Member since Mon, Aug 10, 2020
4 Years ago
;