Reputation: 23
Are if/else statements allowed in react? I have an if/else statement in the render method of my class. It appears that the if/else logic is only followed through the first if statement. When the first condition is met the function returns the expected value. If the first condition is not met all of my else if statements are ignored and the else value is returned.
render() {
if(this.state.navigation === 'welcome') {
return <Welcome goToPage1={this.goToPage1} goToPage2={this.goToPage2} goToPage3={this.goToPage3} goToPage4={this.goToPage4} goToPage5={this.goToPage5} />
}
else if(this.state.naviation === 'page1') {
return <Page1 returnHome={this.returnHome} />
}
else if(this.state.naviation === 'page2') {
return <Page2 returnHome={this.returnHome} />
}
else if(this.state.naviation === 'page3') {
return <Page3 returnHome={this.returnHome} />
}
else if(this.state.naviation === 'page4') {
return <Page4 returnHome={this.returnHome} />
}
else if(this.state.naviation === 'page5') {
return <Page5 returnHome={this.returnHome} />
}
else {
return <h1>ERROR!!</h1>
}
}
Upvotes: 2
Views: 114
Reputation: 2289
For routing, you should use React Router because eventually, you are going to want to start using parameters and authentication, so why reinvent the wheel?
Upvotes: 1
Reputation: 30370
Conditional rendering as you are doing is possible with react.
It looks like you made a minor spelling mistake (naviation rather than navigation) which is causing the unexpected behaviour.
Consider the following revision, which uses a switch/case block instead - this minimises the code needed which can help protect against such errors:
render() {
// Only invoke the this.state.navigation variable once, rather than
// for each return case, which is less error prone
switch(this.state.navigation) {
case 'welcome': {
return <Welcome goToPage1={this.goToPage1} goToPage2={this.goToPage2} goToPage3={this.goToPage3} goToPage4={this.goToPage4} goToPage5={this.goToPage5} />
}
case 'page1': {
return <Page1 returnHome={this.returnHome} />
}
case 'page2': {
return <Page2 returnHome={this.returnHome} />
}
case 'page3': {
return <Page3 returnHome={this.returnHome} />
}
case 'page4': {
return <Page4 returnHome={this.returnHome} />
}
case 'page5': {
return <Page5 returnHome={this.returnHome} />
}
default: {
return <h1>ERROR!!</h1>
}
}
}
Upvotes: 2