⚛️ React Q14 / 113

What is conditional rendering?

AI-Powered Answer ✓ Answered

Conditional rendering in React allows you to render different elements or components based on certain conditions. It's a fundamental concept for creating dynamic user interfaces where the UI changes depending on the application's state or props.

What is Conditional Rendering?

In React, you can create different components that encapsulate the behavior you need. Then, depending on the state of your application, you can render only some of them while hiding others. This ensures that only the relevant parts of the UI are displayed to the user at any given time, leading to more responsive and intuitive applications.

Common Methods for Conditional Rendering

1. Using JavaScript `if` / `else` Statements

The most straightforward way to conditionally render components is by using standard JavaScript if or else statements outside of the JSX, or within the render method but before the return statement.

jsx
function UserGreeting() {
  return <h1>Welcome back!</h1>;
}

function GuestGreeting() {
  return <h1>Please sign up.</h1>;
}

function Greeting(props) {
  const isLoggedIn = props.isLoggedIn;
  if (isLoggedIn) {
    return <UserGreeting />;
  }
  return <GuestGreeting />;
}

2. Element Variables

You can use variables to store elements. This can help conditionally render a part of the component while the rest of the output remains unchanged.

jsx
function LoginButton(props) {
  return (
    <button onClick={props.onClick}>
      Login
    </button>
  );
}

function LogoutButton(props) {
  return (
    <button onClick={props.onClick}>
      Logout
    </button>
  );
}

function LoginControl() {
  const [isLoggedIn, setIsLoggedIn] = React.useState(false);

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

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

  let button;
  if (isLoggedIn) {
    button = <LogoutButton onClick={handleLogoutClick} />;
  } else {
    button = <LoginButton onClick={handleLoginClick} />;
  }

  return (
    <div>
      {button}
    </div>
  );
}

3. Logical `&&` Operator (Short-Circuiting)

When you want to render something only when a condition is true, you can use the logical && operator. If the condition is true, the element after && will be rendered. If false, React ignores and skips it.

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

4. Ternary Operator (Conditional Operator)

For more complex conditions where you need to render either one thing or another, the ternary operator condition ? trueExpression : falseExpression is a concise choice. It works well inline within JSX.

jsx
function UserStatus(props) {
  return (
    <div>
      The user is <b>{props.isLoggedIn ? 'currently' : 'not'}</b> logged in.
    </div>
  );
}

function LightSwitch(props) {
  return (
    <button onClick={props.toggle}>
      {props.isOn ? 'Turn Off' : 'Turn On'}
    </button>
  );
}

5. Preventing Component from Rendering

In rare cases, you might want a component to hide itself even if it was rendered by another component. To do this, return null from its render method.

jsx
function WarningBanner(props) {
  if (!props.warn) {
    return null;
  }

  return (
    <div className="warning">
      Warning!
    </div>
  );
}

Use Cases for Conditional Rendering

  • Displaying different UI elements based on user authentication status (e.g., login/logout buttons, user dashboard vs. public page).
  • Showing or hiding loading spinners or progress bars while data is being fetched.
  • Displaying validation messages based on form input validity.
  • Rendering different components based on application state (e.g., an 'edit' form vs. a 'view' display).
  • Implementing feature flags to enable or disable features for different user groups.
  • Switching between different layouts or themes based on user preferences.