0
0
Reactframework~5 mins

Conditional component rendering in React

Choose your learning style9 modes available
Introduction

Conditional component rendering lets your app show or hide parts based on conditions. It helps make your app interactive and dynamic.

Show a login button only when the user is not logged in.
Display a loading spinner while data is being fetched.
Hide a form after it is submitted successfully.
Show different messages based on user choices.
Syntax
React
function MyComponent({ isLoggedIn }) {
  return (
    <div>
      {isLoggedIn ? <p>Welcome back!</p> : <button>Login</button>}
    </div>
  );
}

Use JavaScript expressions inside curly braces {} to decide what to render.

The ternary operator condition ? truePart : falsePart is common for conditional rendering.

Examples
Shows a message based on time of day.
React
function Greeting({ isMorning }) {
  return <div>{isMorning ? 'Good morning!' : 'Good evening!'}</div>;
}
Uses logical AND to render the message only if show is true.
React
function ShowMessage({ show }) {
  return <div>{show && <p>This message is visible.</p>}</div>;
}
Uses switch to render different components based on status.
React
function Status({ status }) {
  switch (status) {
    case 'loading':
      return <p>Loading...</p>;
    case 'error':
      return <p>Error occurred.</p>;
    default:
      return <p>Ready.</p>;
  }
}
Sample Program

This component shows a login button if the user is not logged in. When clicked, it changes state to logged in and shows a welcome message with a logout button. Clicking logout switches back.

Buttons have aria-label for accessibility.

React
import React, { useState } from 'react';

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

  function handleLogin() {
    setIsLoggedIn(true);
  }

  function handleLogout() {
    setIsLoggedIn(false);
  }

  return (
    <div>
      {isLoggedIn ? (
        <>
          <p>Welcome back!</p>
          <button onClick={handleLogout} aria-label="Logout button">Logout</button>
        </>
      ) : (
        <button onClick={handleLogin} aria-label="Login button">Login</button>
      )}
    </div>
  );
}

export default LoginControl;
OutputSuccess
Important Notes

Always use semantic HTML elements like <button> for clickable items.

Use aria-label to help screen readers describe buttons clearly.

Keep conditions simple to avoid confusing code.

Summary

Conditional rendering lets you show or hide parts of your UI based on data or state.

Use JavaScript expressions inside JSX with {} to decide what to render.

Common patterns include ternary operators, logical AND, and switch statements.