Swiftorial Logo
Home
Swift Lessons
AI Tools
Learn More
Career
Resources

React FAQ: Top 75 Questions

12. What is Conditional Rendering in React?

Conditional rendering in React allows you to render different elements or components based on certain conditions. This is a fundamental concept for building dynamic user interfaces where parts of the UI need to appear or disappear depending on the application's state or props.

Common techniques for conditional rendering include:

  • if statements (outside JSX): You can use standard JavaScript if/else statements within your component's function body (before the return statement) to return different JSX based on a condition.
  • Ternary Operator (condition ? true : false): A concise way to render one thing if a condition is true, and another if it's false, directly within JSX.
  • Logical && Operator (Short-Circuiting): If you want to render something only when a condition is true (and render nothing if it's false), you can use the logical && operator. If the condition is true, the element after && is rendered; otherwise, React ignores it.
  • switch statements: For more complex conditional logic with multiple possible outcomes, a switch statement can be used.
  • Element Variables: You can declare a variable to hold elements, and then conditionally assign JSX to it before rendering that variable.

import React, { useState } from 'react';
import ReactDOM from 'react-dom/client';

// --- Component demonstrating various conditional rendering techniques ---
function UserStatus({ isLoggedIn, userRole }) {
  // 1. Using if/else statement (outside JSX)
  if (!isLoggedIn) {
    return (
      <div className="status-card swf-lsn-card">
        <h3>User Status</h3>
        <p>Please log in.</p>
      </div>
    );
  }

  // 2. Using Element Variables for different messages
  let welcomeMessage;
  if (userRole === 'admin') {
    welcomeMessage = <p className="text-red-600 font-bold">Welcome, Administrator!</p>;
  } else if (userRole === 'moderator') {
    welcomeMessage = <p className="text-blue-600 italic">Welcome, Moderator!</p>;
  } else {
    welcomeMessage = <p>Welcome, User!</p>;
  }

  return (
    <div className="status-card swf-lsn-card">
      <h3>User Status</h3>
      <p>You are currently logged in.</p>

      {welcomeMessage} {/* Rendering the element variable */}

      {/* 3. Using Ternary Operator */}
      <p>
        Your role is: <strong>{userRole ? userRole.toUpperCase() : 'N/A'}</strong>
      </p>

      {/* 4. Using Logical && Operator */}
      {userRole === 'admin' && (
        <p className="text-green-600 mt-2">You have full administrative privileges.</p>
      )}
    </div>
  );
}

// --- App Component ---
function App() {
  const [loggedIn, setLoggedIn] = useState(false);
  const [role, setRole] = useState('user');

  return (
    <div className="app-container swf-lsn-container">
      <h1>Conditional Rendering Demo</h1>
      <div className="mb-4">
        <button
          onClick={() => setLoggedIn(!loggedIn)}
          className="px-4 py-2 mr-2 rounded-md bg-purple-600 text-white"
        >
          {loggedIn ? 'Log Out' : 'Log In'}
        </button>
        <select
          value={role}
          onChange={(e) => setRole(e.target.value)}
          className="px-3 py-2 rounded-md border border-gray-300"
        >
          <option value="user">User</option>
          <option value="moderator">Moderator</option>
          <option value="admin">Admin</option>
        </select>
      </div>
      <UserStatus isLoggedIn={loggedIn} userRole={role} />
      <div className="swf-lsn-list mt-8">
        <p>
          This example demonstrates various ways to conditionally render content
          in React based on the <code>isLoggedIn</code> and <code>userRole</code> props.
        </p>
      </div>
    </div>
  );
}

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>
);
                

Explanation of the Code:

  • The UserStatus component receives isLoggedIn and userRole as props.
  • if statement: At the very beginning, an if (!isLoggedIn) check determines if the user is logged in. If not, it immediately returns a "Please log in" message, preventing the rest of the component from rendering.
  • Element Variables: The welcomeMessage variable is conditionally assigned different JSX elements based on userRole using an if/else if/else structure. This variable is then rendered within the main return statement.
  • Ternary Operator: {userRole ? userRole.toUpperCase() : 'N/A'} is used to display the user's role in uppercase if it exists, otherwise "N/A". This is concise for simple true/false conditions.
  • Logical && Operator: {userRole === 'admin' && (...) } ensures that the "You have full administrative privileges." paragraph is only rendered if userRole is exactly 'admin'. If the condition is false, nothing is rendered.
  • The App component provides buttons and a dropdown to change the isLoggedIn status and userRole, allowing you to observe the conditional rendering in action.