Lesson 7 - Conditional Rendering

7.1 - Conditional Rendering In React

Conditional rendering in React allows you to create components that dynamically display content based on certain conditions. This makes your application more interactive and responsive to user input or state changes.

Conditional rendering enhances user experience by showing or hiding elements based on user actions or the application's state. For example, imagine a button that toggles between "Show Details" and "Hide Details." When the user clicks the button, the detailed information appears or disappears accordingly. This makes the interface cleaner and more intuitive, as users only see relevant content.

Additionally, conditional rendering allows you to display different content based on varying conditions. For instance, consider a scenario where you need to handle user login status. If the user is not logged in, you can display a login form. Once the user logs in, you can show their profile information instead.

Techniques for Conditional Rendering

There are a few techniques available for conditional rendering. Let's explore them.

if Statements You can use the if statements inside the render method to render components based on specific conditions. This is one of the simplest ways to conditionally render elements.

Follow the example below,

import React from 'react';

function App() {
 const isLoggedIn = false;

 if (isLoggedIn) {
 return <h1>Welcome back!</h1>;
 } else {
 return <h1>Please sign up.</h1>;
 }
}

Here, the variable isLoggedIn checks if the user is logged in. We applied an if statement to verify the condition and render the necessary message either Welcome back! or Please sign up.

Ternary Operator This technique is the shortest version of an if statement, allowing you to quickly employ an if statement in a single line. The ternary operator is a more concise way to handle conditional rendering in JSX.

Have a look at the following example,

import React  from 'react';

function App() {
 const num = 5;

 return (
 <div>
 {num < 10 ? <h1>Less then 10</h1> : <h1>Greater then 10</h1>}
 </div>
 );
}

Here, we check if the variable num contains the value less than 10. Then render specific components based on the condition.

Logical && Operator The logical && operator is used to render an element only when a condition is true. If the condition is false, React ignores the element. This allows you to render components that only accept positive responses.

In our example below, we check if the user read the message. Now the component here only renders when the result is positive or true means the user reads the message.

import React  from 'react';

function App() {
 const hasUnreadMessages = true;
 return (
 <div>
 {hasUnreadMessages && <h1>You have unread messages.</h1>}
 </div>
 );
}