You are here: Home / Topics / Chapter 5: Conditional Rendering

Chapter 5: Conditional Rendering

Filed under: React JS Tutorial on 2025-11-20 07:39:16

Introduction to Conditional Rendering
In React, conditional rendering is used to render different UI components based on certain conditions. This is useful for displaying different content based on user interactions, API responses, or other dynamic data.

Using Conditional Statements


To conditionally render components in React, you can use JavaScript conditional statements such as `if-else` or the ternary operator (`?:`). Here's an example:


import React from 'react';

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

In this example, the `UserGreeting` component renders a different message based on the `isLoggedIn` prop.

Using Ternary Operator


You can also use the ternary operator to conditionally render components:


import React from 'react';

function UserGreeting(props) {
 return (
   <div>
     {props.isLoggedIn ? <h1>Welcome back!</h1> : <h1>Please sign up.</h1>}
   </div>
 );
}

Using Logical AND Operator


You can use the logical AND operator (`&&`) to conditionally render components:
import React from 'react';

function Mailbox(props) {
 return (
   <div>
     <h1>Hello!</h1>
     {props.unreadMessages.length > 0 &&
       <h2>You have {props.unreadMessages.length} unread messages.</h2>
     }
   </div>
 );
}

In this example, the `h2` element is only rendered if `unreadMessages.length` is greater than 0.

Example Code


Here's an example of a simple React app that uses conditional rendering:


import React, { useState } from 'react';

function Toggle() {
 const [isToggleOn, setIsToggleOn] = useState(false);

 return (
   <div>
     {isToggleOn ? <h1>ON</h1> : <h1>OFF</h1>}
     <button onClick={() => setIsToggleOn(!isToggleOn)}>Toggle</button>
   </div>
 );
}

 

Here's a practice exercise:

Create a simple React app that displays a login form. If the user is logged in, display a welcome message. If not, display the login form.

Hint: Use the `useState` hook to store the user's login status. Use conditional rendering to display the welcome message or the login form.


About Author:
A
Ankit Singh     View Profile
Hi, I am using MCQ Buddy. I love to share content on this website.