patternreactCritical
Is it possible to use if...else... statement in React render function?
Viewed 0 times
useelsestatementfunctionrenderreactpossible
Problem
Basically, I have a react component, its
render() function body is as below: (It is my ideal one, which means it currently does not work)render(){
return (
// note: logic only, code does not work here
if (this.props.hasImage)
else
)
}
Solution
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.
You can also deal with it inside the render function, but before returning the jsx.
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
render() {
const isLoggedIn = this.state.isLoggedIn;
return (
{isLoggedIn ? (
) : (
)}
);
}You can also deal with it inside the render function, but before returning the jsx.
if (isLoggedIn) {
button = ;
} else {
button = ;
}
return (
{button}
);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 (
Hello!
{unreadMessages.length > 0 &&
You have {unreadMessages.length} unread messages.
}
);Code Snippets
render() {
const isLoggedIn = this.state.isLoggedIn;
return (
<div>
{isLoggedIn ? (
<LogoutButton onClick={this.handleLogoutClick} />
) : (
<LoginButton onClick={this.handleLoginClick} />
)}
</div>
);
}if (isLoggedIn) {
button = <LogoutButton onClick={this.handleLogoutClick} />;
} else {
button = <LoginButton onClick={this.handleLoginClick} />;
}
return (
<div>
<Greeting isLoggedIn={isLoggedIn} />
{button}
</div>
);return (
<div>
<h1>Hello!</h1>
{unreadMessages.length > 0 &&
<h2>
You have {unreadMessages.length} unread messages.
</h2>
}
</div>
);Context
Stack Overflow Q#40477245, score: 526
Revisions (0)
No revisions yet.