TutorialsArena

React Conditional Rendering: Dynamically Displaying UI Elements

Learn how to implement conditional rendering in React to create dynamic and responsive user interfaces. This tutorial covers various techniques, including `if` statements, the logical AND operator, and ternary operators, enhancing the interactivity and adaptability of your React applications.



Conditional Rendering in React

What is Conditional Rendering?

Conditional rendering in React allows you to dynamically display different UI elements based on certain conditions. This makes your applications more interactive and responsive to user input and application state. You use JavaScript expressions to determine which components or elements to render.

Methods for Conditional Rendering

Several techniques are commonly used:

  • if statements
  • Ternary operator (condition ? true : false)
  • Logical AND operator (condition && element)
  • switch statements
  • Using enums (for improved readability with multiple conditions)

Conditional Rendering with if Statements

The simplest approach is using an if statement within the `render()` method to conditionally return different JSX. This is suitable for simple conditional rendering within a component.

if Statement Example

const SignUp = ({ isLoggedIn }) => {
  if (isLoggedIn) {
    return <UserLoggin />;
  } else {
    return <GuestLoggin />;
  }
};

Conditional Rendering with the Logical AND Operator (&&)

The logical AND operator provides a concise way to conditionally render elements. If the condition is true, the element following && is rendered; otherwise, it's skipped.

&& Operator Example

{isLoggedIn && <p>Welcome Back!</p>}

Conditional Rendering with the Ternary Operator

The ternary operator provides a concise alternative to if-else statements. It's particularly useful when you have two possible outputs based on a single condition.

Ternary Operator Example

<p>Welcome {isLoggedIn ? 'Back' : 'Please login first'}</p>

Conditional Rendering with switch Statements

switch statements are helpful when you have multiple conditions to check based on the value of a single variable.

switch Statement Example

const NotificationMsg = ({ text }) => {
  switch (text) {
    case 'Hi All': return <p>Hi All!</p>;
    case 'Hello JavaTpoint': return <p>Hello JavaTpoint!</p>;
    default: return null;
  }
};

Conditional Rendering with Enums

Enums provide a more readable way to handle multiple conditional renderings, especially when mapping states to different UI elements.

Enum Example

const notificationTypes = {
  info: <p>Info message</p>,
  warning: <p>Warning message</p>,
};

const NotificationMsg = ({ state }) => notificationTypes[state] || null;

React Login/Logout Component with Conditional Rendering

This example demonstrates how to toggle between login and logout states using conditional rendering in React.

Example: Login/Logout Component

import React, { useState } from 'react';

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

    const handleLogin = () => {
        setIsLoggedIn(true);
    };

    const handleLogout = () => {
        setIsLoggedIn(false);
    };

    return (
        <div>
            <h2>Conditional Rendering in React</h2>
            {isLoggedIn ? (
                <div>
                    <p>Welcome back, User!</p>
                    <button onClick={handleLogout}>Logout</button>
                </div>
            ) : (
                <div>
                    <p>Please log in.</p>
                    <button onClick={handleLogin}>Login</button>
                </div>
            )}
        </div>
    );
}

export default AuthComponent;

How It Works:

  • useState Hook: Manages the authentication state.
  • Conditional Rendering: Uses a ternary operator to switch between login and logout states.
  • Event Handlers: `handleLogin` and `handleLogout` update the state accordingly.

Preventing Component Rendering

To prevent a component from rendering, return null from its `render()` method.

Preventing Rendering

const Show = ({ displayMessage }) => {
  if (!displayMessage) return null;
  return <p>Component is rendered</p>;
};