Conditional Rendering
Conditional Rendering
- Conditional Rendering works the same as conditions work in other programming languages.
- Condition rendering, we render depending on some condition.
- For example, handling the login/logout button.
- There are 3 ways to do conditional rendering: if, ternary operator, and logical && operator
IF
-
It is the easiest way for having conditional rendering.
-
If the condition is true, it will return the element to be rendered.
function UserLoggin(props) {
return <h1>Welcome back!</h1>;
}
function GuestLoggin(props) {
return <h1>Please sign up.</h1>;
}
function SignUp(props) {
const isLoggedIn = props.isLoggedIn;
if (isLoggedIn) {
return <UserLogin />;
}
return <GuestLogin />;
}
ReactDOM.render(
<SignUp isLoggedIn={false} />,
document.getElementById('root')
);
Logical && operator
- The operator is checking the condition, if the condition is true element right after && will dislay in output and If it is false, it will ignore and skip it.
import React from 'react';
function App()
{
return(<div>
{
(10>=5) && alert('Hello Users!')
}
</div>
);
}
export default App;
Ternary operator
- It is inline if-else operator.
- It takes three operands. If the condition is true, statement1 will be rendered else statement 2.
- Syntax:
condition?true:false
render() {
const isLoggedIn = this.state.isLoggedIn;
return (
<div>
{isLoggedIn
? <LogoutButton onClick={this.handleLogoutClick} />
: <LoginButton onClick={this.handleLoginClick} />
}
</div>
);
}