ternary operator conditional rendering react code example
Example 1: ternary operator react
render () {
return (
<div className="row">
{
(this.state.message === 'failed')
? <div> Something went wrong </div>
: <div> Everything in the world is fine </div>
}
</div>
);
}
Example 2: if else render react
render() {
const isLoggedIn = this.state.isLoggedIn;
return (
<div>
{isLoggedIn ? (
<LogoutButton onClick={this.handleLogoutClick} />
) : (
<LoginButton onClick={this.handleLoginClick} />
)}
</div>
);
}
Example 3: ternary react
render() {
const isLoggedIn = this.state.isLoggedIn;
return (
<div>
The user is <b>{isLoggedIn ? 'currently' : 'not'}</b> logged in.
</div>
);
}
Example 4: conditional rendering react
import React, { Component } from 'react';
export class HeroComponent extends Component
{
render() {
return (
<section className={"hero" + (this.props.type ? " " + this.props.type + " " : " ") + this.props.size}>
<div className="hero-body">
<div className={"container" + this.props.alignment ? " " + this.props.alignment : ""}>
<h1 className="title">{this.props.heading}</h1>
{this.props.subheading && <h2 className="subtitle">{this.props.subheading}</h2>}
</div>
</div>
</section>
)
}
}