render component conditionally react 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: react native conditional rendering
class Component extends React.Component {
const a = true
render() {
return (
<Container>
{a == true
? (<Button/>)
: null
}
</Container>
)
}
}
This is staying: if a == true, render a button component.
Otherwise render null, in other words nothing.
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: react native conditional rendering
function Mailbox(props) {
const unreadMessages = props.unreadMessages;
return (
<div>
<h1>Hello!</h1>
{unreadMessages.length > 0 &&
<h2>
You have {unreadMessages.length} unread messages.
</h2>
}
</div>
);
}
Example 5: conditional rendering react
function Mailbox(props) {
const unreadMessages = props.unreadMessages;
return (
<div>
<h1>Hello!</h1>
{unreadMessages.length > 0 && <h2> You have {unreadMessages.length} unread messages. </h2> } </div>
);
}
const messages = ['React', 'Re: React', 'Re:Re: React'];
ReactDOM.render(
<Mailbox unreadMessages={messages} />,
document.getElementById('root')
);
Example 6: 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>
)
}
}