Is it possible to use if...else... statement in React render function?
There actually is a way to do exactly what OP is asking. Just render and call an anonymous function like so:
render () {
return (
<div>
{(() => {
if (someCase) {
return (
<div>someCase</div>
)
} else if (otherCase) {
return (
<div>otherCase</div>
)
} else {
return (
<div>catch all</div>
)
}
})()}
</div>
)
}
Not exactly like that, but there are workarounds. There's a section in React's docs about conditional rendering that you should take a look. Here's an example of what you could do using inline if-else.
render() {
const isLoggedIn = this.state.isLoggedIn;
return (
<div>
{isLoggedIn ? (
<LogoutButton onClick={this.handleLogoutClick} />
) : (
<LoginButton onClick={this.handleLoginClick} />
)}
</div>
);
}
You can also deal with it inside the render function, but before returning the jsx.
if (isLoggedIn) {
button = <LogoutButton onClick={this.handleLogoutClick} />;
} else {
button = <LoginButton onClick={this.handleLoginClick} />;
}
return (
<div>
<Greeting isLoggedIn={isLoggedIn} />
{button}
</div>
);
It's also worth mentioning what ZekeDroid brought up in the comments. If you're just checking for a condition and don't want to render a particular piece of code that doesn't comply, you can use the && operator
.
return (
<div>
<h1>Hello!</h1>
{unreadMessages.length > 0 &&
<h2>
You have {unreadMessages.length} unread messages.
</h2>
}
</div>
);