React Conditional Rendering

React Conditional Rendering

Conditional rendering in React allows components to display different content based on conditions. This helps in creating dynamic and interactive UIs.

1. Using if Statements

In React, you can use `if` statements outside JSX to determine what to render.

Example 1️⃣: Using if Statement (Function Component)

function Greeting(props) {
if (props.isLoggedIn) {
return <h1>Welcome back!</h1>;
}
return <h1>Please log in.</h1>;
}

🔹 How It Works:

•  If isLoggedIn is true, it returns “Welcome back!”.
•  If isLoggedIn is false, it returns “Please log in.”.

Example 2️⃣: Using if Inside a Class Component

import React, { Component } from ‘react’;

class Greeting extends Component {
render() {
if (this.props.isLoggedIn) {
return <h1>Welcome back!</h1>;
}
return <h1>Please log in.</h1>;
}
}

export default Greeting;

Why Use This?

  Works well in older React versions (before hooks).
  Uses this.props.isLoggedIn to decide what to display.

Example 3️⃣: Using if-else Inside JSX (Not Allowed)

// This will not work inside JSX
return (
<div>
{if (isLoggedIn) { <h1>Welcome back!</h1>; } else { <h1>Please log in.</h1>; }}
</div>
);

Why?

  JSX does not allow direct if-else inside {}.
•  Use a Ternary Operator Instead:

return <h1>{isLoggedIn ? “Welcome back!” : “Please log in.”}</h1>;

2. Using Ternary Operator

The ternary operator allows inline conditional rendering inside JSX.

Example 1️⃣: Using Ternary Operator in a Function Component

The ternary operator allows inline conditional rendering inside function Greeting(props) {
return <h1>{props.isLoggedIn ? “Welcome back!” : “Please log in.”}</h1>;
}JSX.

🔹 How It Works:

  If isLoggedIn is true, it displays “Welcome back!”.
  If isLoggedIn is false, it displays “Please log in.”.

Example 2️⃣: Using Ternary Operator in a Class Component

import React, { Component } from ‘react’;

class Greeting extends Component {
render() {
return <h1>{this.props.isLoggedIn ? “Welcome back!” : “Please log in.”}</h1>;
}
}

export default Greeting;

🔹 Why Use This?

  Shortens if-else statements inside JSX.
•  Ideal for simple conditional rendering.

Example 3️⃣: Toggling Login Status with a Button

import React, { useState } from ‘react’;

function App() {
const [isLoggedIn, setIsLoggedIn] = useState(false);

return (
<div>
<h1>{isLoggedIn ? “Welcome back!” : “Please log in.”}</h1>
<button onClick={() => setIsLoggedIn(!isLoggedIn)}>
{isLoggedIn ? “Logout” : “Login”}
</button>
</div>
);
}

export default App;

🔹 What Happens Here?

✔ useState(false) initializes isLoggedIn as false.
✔ Clicking the button toggles the state between “Login” and “Logout”.
✔ The heading changes dynamically.

3. Using Logical && Operator

The logical AND (&&) operator is useful when you want to conditionally render an element only when a condition is true.

Example 1️⃣: Displaying Notifications

function Notification(props) {
return (
<div>
<h1>Dashboard</h1>
{props.hasMessages && <p>You have new messages!</p>}
</div>
);
}

// Usage:
export default function App() {
return <Notification hasMessages={true} />;
}

🔹 How It Works?

•  If props.hasMessages === true, the <p> element is rendered.
  If false, nothing appears (it doesn’t return null or undefined).

Example 2️⃣: Show/Hide Button Based on State

import React, { useState } from “react”;

function ShowButton() {
const [isLoggedIn, setIsLoggedIn] = useState(false);

return (
<div>
<h1>Welcome to My App</h1>
{!isLoggedIn && <button onClick={() => setIsLoggedIn(true)}>Login</button>}
{isLoggedIn && <button onClick={() => setIsLoggedIn(false)}>Logout</button>}
</div>
);
}

export default ShowButton;

🔹 What Happens Here?

✔ If isLoggedIn === false, a “Login” button appears.
✔ After clicking, it switches to “Logout” dynamically.

Example 3️⃣: Conditional UI Elements

function UserProfile({ isPremium }) {
return (
<div>
<h2>User Profile</h2>
{isPremium && <p>⭐ Premium Member</p>}
{!isPremium && <p>Join Premium for more benefits!</p>}
</div>
);
}

// Usage:
export default function App() {
return <UserProfile isPremium={true} />;
}

🔹 Why Use && Here?

✔ If isPremium === true, it shows the “⭐ Premium Member” text.
✔ Otherwise, it displays a message prompting the user to upgrade.

4. Using Switch Case for Multiple Conditions

For handling multiple conditions, you can use a switch statement.

Example 1️⃣: Handling Different Status Messages

function StatusMessage(props) {
switch (props.status) {
case “loading”:
return <p>Loading…</p>;
case “success”:
return <p>Data loaded successfully!</p>;
case “error”:
return <p>Something went wrong.</p>;
default:
return <p>Unknown status.</p>;
}
}

🔹 How It Works:

  Depending on the value of props.status, it renders a different message.

Example 2️⃣: Switch-Case with a Dynamic State in Function Component

import React, { useState } from “react”;

function App() {
const [status, setStatus] = useState(“loading”);

return (
<div>
<StatusMessage status={status} />
<button onClick={() => setStatus(“loading”)}>Set Loading</button>
<button onClick={() => setStatus(“success”)}>Set Success</button>
<button onClick={() => setStatus(“error”)}>Set Error</button>
</div>
);
}

function StatusMessage({ status }) {
switch (status) {
case “loading”:
return <p>Loading…</p>;
case “success”:
return <p>Data loaded successfully!</p>;
case “error”:
return <p>Something went wrong.</p>;
default:
return <p>Unknown status.</p>;
}
}

export default App;

🔹 What's Happening?

✔ useState(“loading”) sets the initial status.
✔ Clicking a button updates the status dynamically.
✔ switch renders the correct message.

Example 3️⃣: Switch-Case Inside a Class Component

import React, { Component } from “react”;

class StatusMessage extends Component {
render() {
switch (this.props.status) {
case “loading”:
return <p>Loading…</p>;
case “success”:
return <p>Data loaded successfully!</p>;
case “error”:
return <p>Something went wrong.</p>;
default:
return <p>Unknown status.</p>;
}
}
}

export default StatusMessage;

🔹 Why Use This?

  Works well in class-based components.
  Keeps conditional rendering cleaner than multiple if-else statements.

5. Conditional Rendering Using IIFE in React

An Immediately Invoked Function Expression (IIFE) is useful for keeping conditions inside JSX without extra variables or if statements outside JSX.

Example 1️⃣: Simple Login Status Check

function UserStatus(props) {
return (
<div>
{(() => {
if (props.isLoggedIn) return <h1>Welcome back!</h1>;
return <h1>Please log in.</h1>;
})()}
</div>
);
}

🔹 How It Works?

  An IIFE (Immediately Invoked Function Expression) is wrapped in {} inside JSX.
  The function runs immediately and returns either “Welcome back!” or “Please log in.”

Example 2️⃣: Multiple Conditions with User Roles

function UserGreeting({ role }) {
return (
<div>
{(() => {
if (role === “admin”) return <h1>Welcome, Admin!</h1>;
if (role === “editor”) return <h1>Welcome, Editor!</h1>;
if (role === “user”) return <h1>Welcome, User!</h1>;
return <h1>Please log in.</h1>;
})()}
</div>
);
}

export default function App() {
return <UserGreeting role=”admin” />;
}

🔹 Why Use This?

✔ Clean JSX with multiple conditions inside {}
✔ Avoids extra if-else statements outside JSX
✔ Works great for small conditional logic

Example 3️⃣: Conditional Button Rendering

import React, { useState } from “react”;

function App() {
const [isSubscribed, setIsSubscribed] = useState(false);

return (
<div>
{(() => {
if (isSubscribed) {
return <button onClick={() => setIsSubscribed(false)}>Unsubscribe</button>;
}
return <button onClick={() => setIsSubscribed(true)}>Subscribe</button>;
})()}
</div>
);
}

export default App;

🔹 What Happens Here?

•  When isSubscribed === false, a “Subscribe” button appears.
•  When clicked, it changes to “Unsubscribe” using setIsSubscribed(true).

6. Conditional Rendering with Higher-Order Components (HOC)

A Higher-Order Component (HOC) is a function that takes a component as an argument and returns a new component with enhanced behavior.
This technique is useful for conditionally rendering components based on authentication, permissions, or other conditions.

Example 1️⃣: Protecting a Component with Authentication

Example 1️⃣: Protecting a Component with Authenticationimport React from “react”;

// Higher-Order Component (HOC) for Authentication
function withAuth(Component) {
return function AuthenticatedComponent(props) {
if (!props.isAuthenticated) {
return <p>Access Denied</p>;
}
return <Component {…props} />;
};
}

// Component that needs authentication
function Dashboard() {
return <h1>Welcome to the Dashboard!</h1>;
}

// Wrapping the Dashboard with the HOC
const ProtectedDashboard = withAuth(Dashboard);

// Usage
export default function App() {
return <ProtectedDashboard isAuthenticated={true} />;
}

🔹 What Happens Here?

✔ The withAuth function takes a component (Component) as an argument.
✔ It checks props.isAuthenticated before rendering the component.
✔ If the user is not authenticated, it displays “Access Denied” instead.
✔ Otherwise, it renders the original Dashboard component.

Example 2️⃣: HOC for Feature Access Control

function withFeatureAccess(Component) {
return function FeatureComponent(props) {
return props.hasFeature ? <Component {…props} /> : <p>Feature Unavailable</p>;
};
}

function PremiumContent() {
return <h1>Exclusive Premium Content</h1>;
}

const ProtectedContent = withFeatureAccess(PremiumContent);

export default function App() {
return <ProtectedContent hasFeature={false} />;
}

🔹 What Happens Here?

✔ If hasFeature is true, the user sees “Exclusive Premium Content”.
✔ If false, it shows “Feature Unavailable” instead.

Example 3️⃣: HOC for Role-Based Access

function withRole(Component, requiredRole) {
return function RoleBasedComponent(props) {
return props.role === requiredRole ? <Component {…props} /> : <p>Access Restricted</p>;
};
}

function AdminPanel() {
return <h1>Admin Dashboard</h1>;
}

const ProtectedAdmin = withRole(AdminPanel, “admin”);

export default function App() {
return <ProtectedAdmin role=”user” />;
}

🔹 How It Works?

✔ withRole(AdminPanel, “admin”) only allows users with “admin” role.
✔ If a non-admin tries to access, they see “Access Restricted”.

Conclusion

Conditional rendering is a powerful tool in React that allows you to build flexible and dynamic UIs. You can choose the best method depending on the complexity and readability of your component.

Course Video in English

Chatbot