React Conditional Rendering
- In React, we can create multiple components to encapsulate specific behavior. These components can then be rendered based on certain conditions or the application's state. In other words, depending on one or more conditions, a component determines which elements to return. Conditional rendering in React works just like conditional statements in JavaScript, where JavaScript operators are used to create elements that reflect the current state, and React updates the UI accordingly.
- From this scenario, we can understand how conditional rendering works in React. For example, consider handling a login/logout button. The login and logout buttons would be separate components. If the user is logged in, the logout component is rendered to display the logout button. If the user is not logged in, the login component is rendered to display the login button. This is an example of conditional rendering in React.
- There are several ways to implement conditional rendering in React, including:
- ternary operator
- logical && operator
- switch case operator
- Conditional rendering with enums
If
The `if` statement is one of the simplest ways to implement conditional rendering in React within the render method. It applies to the entire component block. If the condition is true, it will return the element to be rendered. This can be seen in the example below.
Example
function AdminDashboard(props) {
return <h1>Welcome, Admin!</h1>;
}
function UserDashboard(props) {
return <h1>Welcome, User!</h1>;
}
function Dashboard(props) {
const isAdmin = props.isAdmin;
if (isAdmin) {
return <AdminDashboard />;
}
return <UserDashboard />;
}
ReactDOM.render(
<Dashboard isAdmin={true} />,
document.getElementById('root')
);
Logical && operator
This operator is used to check a condition. If the condition is true, it will return the element immediately after the `&&`, and if the condition is false, React will ignore and skip rendering it.
Syntax
{
condition &&
// whatever written after && will be a part of output.
}
The behavior of this concept can be understood from the example below.
If you run the code, you won't see the alert message because the condition is not met.
('gocourse' == 'Gocourse') && alert('This alert will never be shown!')
If you run the code below, you will see the alert message because the condition is met.
(10 > 5) && alert('This alert will be shown!')
Example
import React from 'react';
import ReactDOM from 'react-dom';
// Example Component
function Example() {
return (
<div>
{
(5 < 10) && console.log('This message will be logged!')
}
</div>
);
}
ReactDOM.render(<Example />, document.getElementById('root'));
As seen in the output above, the alert message is successfully displayed on the screen because the condition (10 > 5) evaluates to true.
Ternary operator
The ternary operator is used when two blocks alternate based on a certain condition. It makes your if-else statement more concise by taking three operands and serves as a shortcut for the if statement.
Syntax
condition ? true : false
If the condition is true, statement1 will be rendered; otherwise, statement2 will be rendered.
Example
render() {
const isAdmin = this.state.isAdmin;
return (
<div>
{isAdmin ? 'Welcome, Admin!' : 'You do not have admin access.'}
</div>
);
}
Switch case operator
Sometimes, multiple conditional renderings are needed. In such cases, the switch case can be used to apply conditional rendering based on different states.
Example
function UserRole({ role }) {
switch (role) {
case 'Admin':
return <div>Welcome, Admin! You have full access.</div>;
case 'Editor':
return <div>Welcome, Editor! You can edit content.</div>;
case 'Viewer':
return <div>Welcome, Viewer! You can only view content.</div>;
default:
return <div>Please log in to access the system.</div>;
}
}
Conditional Rendering with enums
An enum is an excellent way to handle multiple conditional renderings. It is more readable than the switch case operator and is ideal for mapping between different states. It's also well-suited for handling multiple conditions. This can be demonstrated in the example below.
Example
function UserStatus({ status, username }) {
return (
<div>
{{
online: <div>{username} is online</div>,
offline: <div>{username} is offline</div>,
away: <div>{username} is away</div>,
}[status] || <div>{username}'s status is unknown</div>}
</div>
);
}
Conditional Rendering Example
In the example below, we have created a stateful component called `App` that manages the login control. It includes three components: `Logout`, `Login`, and `Message`. The `App` component will render either one of these components depending on its current state.
import React, { Component } from 'react';
// Welcome Component
function Welcome(props) {
return <h1>Hello, {props.username}!</h1>;
}
// Guest Component
function Guest() {
return <h1>Welcome, Guest! Please sign up.</h1>;
}
// SignUp Component
function SignUp(props) {
return <button onClick={props.handleSignUp}>Sign Up</button>;
}
// SignOut Component
function SignOut(props) {
return <button onClick={props.handleSignOut}>Sign Out</button>;
}
class App extends Component {
constructor(props) {
super(props);
this.handleSignUp = this.handleSignUp.bind(this);
this.handleSignOut = this.handleSignOut.bind(this);
this.state = { isSignedUp: false, username: '' };
}
handleSignUp() {
this.setState({ isSignedUp: true, username: 'John Doe' });
}
handleSignOut() {
this.setState({ isSignedUp: false, username: '' });
}
render() {
return (
<div>
<h1>Conditional Rendering Example</h1>
{this.state.isSignedUp ? (
<div>
<Welcome username={this.state.username} />
<SignOut handleSignOut={this.handleSignOut} />
</div>
) : (
<div>
<Guest />
<SignUp handleSignUp={this.handleSignUp} />
</div>
)}
</div>
);
}
}
export default App;
Output
When you run the above code, you will see the following screen.
After clicking the logout button, the screen will update to the one shown below.
Preventing Component form Rendering
Sometimes, a component may need to hide itself even if it was rendered by another component. To achieve this (i.e., prevent the component from rendering), we can return `null` instead of its render output. This can be illustrated in the example below:
Example
In this example, the component is rendered based on the value of the `displayMessage` prop. If the prop value is false, the component will not be rendered.
import React from 'react';
import ReactDOM from 'react-dom';
function Notification(props) {
if (!props.showNotification)
return null;
else
return <div>Your subscription is active!</div>;
}
ReactDOM.render(
<div>
<h1>Subscription Status</h1>
<Notification showNotification={false} />
</div>,
document.getElementById('app')
);