0
0
Reactframework~5 mins

Why conditional rendering is needed in React

Choose your learning style9 modes available
Introduction

Conditional rendering lets your app show or hide parts based on what is happening. It helps make your app smart and interactive.

Show a login button only when the user is not logged in.
Display a loading spinner while data is being fetched.
Hide or show a message based on user actions.
Switch between different views or pages inside the same component.
Syntax
React
return condition ? <ComponentA /> : <ComponentB />;

// or using && operator
return condition && <Component />;
Use the ternary operator to choose between two components or elements.
Use the && operator to show something only if the condition is true.
Examples
Shows a welcome message if logged in, otherwise asks to sign in.
React
function Greeting({ isLoggedIn }) {
  return isLoggedIn ? <h1>Welcome back!</h1> : <h1>Please sign in.</h1>;
}
Shows "Loading..." text only when isLoading is true.
React
function Loading({ isLoading }) {
  return isLoading ? <p>Loading...</p> : null;
}
Sample Program

This app shows a login or logout button and message based on whether the user is logged in. Clicking the button switches the state and updates the view.

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

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

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

export default App;
OutputSuccess
Important Notes

Conditional rendering keeps your UI clean and relevant to the user.

Always return valid React elements or null when condition is false.

Summary

Conditional rendering controls what the user sees based on app state.

Use ternary or && operators to show or hide components easily.

This makes your app interactive and user-friendly.