use if condition in jsx code example
Example 1: if else render react
render() {
const isLoggedIn = this.state.isLoggedIn;
return (
<div>
{isLoggedIn ? (
<LogoutButton onClick={this.handleLogoutClick} />
) : (
<LoginButton onClick={this.handleLoginClick} />
)}
</div>
);
}
Example 2: ternary react
render() {
const isLoggedIn = this.state.isLoggedIn;
return (
<div>
The user is <b>{isLoggedIn ? 'currently' : 'not'}</b> logged in.
</div>
);
}
Example 3: react if statement
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>
)
}
}