1. Home
  2. Coding Hub
  3. Coding Notes
  4. React
  5. Conditional Rendering
45% OFFBLACK FRIDAY SALE
Sale ends in
03Days
00Hrs
19Mins
43Secs
Claim
  1. Home
  2. Coding Hub
  3. Coding Notes
  4. React
  5. Conditional Rendering

Limited time offer

45% OFF

BLACK FRIDAY SALE

Sale ends in

03Days
00Hrs
19Mins
43Secs
Claim
HTMLCSSJavaScriptPythonJavaC++React.jsSQLNext.jsNode.js
Underrated CoderUnderrated Coder
Underrated CoderUnderrated Coder
Resources
  • Coding Hub
  • Roadmap
  • DSA Sheet
  • Coding Notes
  • Coding Quiz
  • Code Compiler
  • Coder AI
Interview Preparation
  • 1:1 Mentorship
  • Interview Q&A
Community
  • Blog
  • Coder Community
Help & Support
  • Contact Us
  • Troubleshooting
  • Report a Bug
HTMLCSSJavaScriptPythonJavaC++React.jsSQLNext.jsNode.js
Outline
React IntroductionSetup & ViteJSX SyntaxVirtual DOMFunction ComponentsComponent TreeReact Fragments
Passing PropsDestructuring PropsChildren PropConditional RenderingList RenderingReact KeysCSS Modules
Event HandlingSynthetic EventsState BasicsuseState HookState BatchingObject StateArray State
useEffect HookDependency ArrayCleanup FunctionsData FetchingStrict Mode
useRef HookPassing Refs (forwardRef)useReducer HookCustom HooksuseId Hook
Prop Drilling ProblemContext APIuseContext HookRedux IntroZustand Alternative
React Router DOMRoute ParametersNested RoutesControlled InputsReact Hook Form
React.memouseMemo HookuseCallback HookCode Splitting (lazy)Bundle Size Optimization
React Server ComponentsClient ComponentsSuspense for Data FetchingNext.js App RouterServer ActionsuseTransition HookReact 19 Forms (useActionState)
React.js

Conditional Rendering

Overview

In modern applications, the UI is rarely static. You need to show a 'Logout' button if a user is logged in, but a 'Login' button if they aren't. You need to show a spinning loader while data fetches, and a table once it arrives.

In React, because JSX is ultimately just JavaScript, you handle Conditional Rendering using standard JavaScript logic: if/else statements, the ternary operator ? :, and the logical AND && operator.

Because JSX inside a return statement does not support traditional block-level if statements, developers universally rely on ternaries for if/else conditions, and the && operator when they want to render something only if a condition is true (and render absolutely nothing otherwise).

Syntax

The 3 Methods of Conditional Rendering
jsx
function AuthPanel({ isLoggedIn, hasNotifications }) {
  // Method 1: Early Return (Standard IF Statement)
  // Great for stopping the entire component from rendering
  if (isLoggedIn === null) {
    return <p>Loading user data...</p>;
  }

  return (
    <div className="panel">
      {/* Method 2: Ternary Operator (If / Else) */}
      {/* Used for choosing between two distinct UI elements */}
      {isLoggedIn ? <LogoutButton /> : <LoginButton />}

      {/* Method 3: Logical AND (If True, Do This. Else, Do Nothing) */}
      {/* Used when you only want to show an element if a condition is met */}
      {hasNotifications && <span className="badge">New Alerts!</span>}
    </div>
  );
}

Common Pitfalls

  • The Zero (0) Trap with Logical AND (&&): If you write {array.length && <List />} and the array is empty (length is 0), React will actually render the number '0' on the screen! This is because in JS, 0 is falsy, so the && short-circuits and returns 0. To fix this, always make the left side a strict boolean: {array.length > 0 && <List />}.

Interview Questions

Why can't you use a standard 'if' statement directly inside the JSX of a return block?

JSX is syntactic sugar that compiles into function calls (React.createElement()). You cannot place a block-level if statement inside a function argument in JavaScript. However, you can use expressions like ternaries (? :) because they evaluate to a specific value that can be passed as an argument.

How do you prevent a component from rendering entirely?

You can return null from the component. If a component returns null, React simply ignores it and renders nothing to the DOM for that specific branch of the tree.

Real-World Example

Data Fetching State UI: This is the exact pattern used in every production application. Early returns cleanly handle loading and error states at the top of the file, while ternaries and logical ANDs handle granular UI toggles within the main layout.

example
jsx
function Dashboard() {
  const { data, isLoading, error } = useFetchData('/api/stats');

  // 1. Error state (Early return)
  if (error) {
    return <div className="error-banner">Critical Error: {error.message}</div>;
  }

  // 2. Loading state (Early return)
  if (isLoading) {
    return <Spinner className="w-8 h-8 animate-spin" />;
  }

  // 3. Success state
  return (
    <main>
      <h1>Dashboard Analytics</h1>
      {/* Only render the premium chart if the user is a pro tier */}
      {data.isProUser && <PremiumChart data={data.charts} />}
      
      {/* Ternary for empty states */}
      {data.transactions.length > 0 
        ? <TransactionTable rows={data.transactions} />
        : <p className="text-gray-500">No transactions found this month.</p>
      }
    </main>
  );
}

Check Your Knowledge

Test your understanding of Conditional Rendering with these quick questions.

Question 1

Which operator is best used when you want to render a component if a condition is true, but render NOTHING if it is false?

Question 2

What happens if you evaluate `{ 0 && <Component /> }` inside JSX?

Take React Quiz
Outline
React IntroductionSetup & ViteJSX SyntaxVirtual DOMFunction ComponentsComponent TreeReact Fragments
Passing PropsDestructuring PropsChildren PropConditional RenderingList RenderingReact KeysCSS Modules
Event HandlingSynthetic EventsState BasicsuseState HookState BatchingObject StateArray State
useEffect HookDependency ArrayCleanup FunctionsData FetchingStrict Mode
useRef HookPassing Refs (forwardRef)useReducer HookCustom HooksuseId Hook
Prop Drilling ProblemContext APIuseContext HookRedux IntroZustand Alternative
React Router DOMRoute ParametersNested RoutesControlled InputsReact Hook Form
React.memouseMemo HookuseCallback HookCode Splitting (lazy)Bundle Size Optimization
React Server ComponentsClient ComponentsSuspense for Data FetchingNext.js App RouterServer ActionsuseTransition HookReact 19 Forms (useActionState)
React.js

Conditional Rendering

Overview

In modern applications, the UI is rarely static. You need to show a 'Logout' button if a user is logged in, but a 'Login' button if they aren't. You need to show a spinning loader while data fetches, and a table once it arrives.

In React, because JSX is ultimately just JavaScript, you handle Conditional Rendering using standard JavaScript logic: if/else statements, the ternary operator ? :, and the logical AND && operator.

Because JSX inside a return statement does not support traditional block-level if statements, developers universally rely on ternaries for if/else conditions, and the && operator when they want to render something only if a condition is true (and render absolutely nothing otherwise).

Syntax

The 3 Methods of Conditional Rendering
jsx
function AuthPanel({ isLoggedIn, hasNotifications }) {
  // Method 1: Early Return (Standard IF Statement)
  // Great for stopping the entire component from rendering
  if (isLoggedIn === null) {
    return <p>Loading user data...</p>;
  }

  return (
    <div className="panel">
      {/* Method 2: Ternary Operator (If / Else) */}
      {/* Used for choosing between two distinct UI elements */}
      {isLoggedIn ? <LogoutButton /> : <LoginButton />}

      {/* Method 3: Logical AND (If True, Do This. Else, Do Nothing) */}
      {/* Used when you only want to show an element if a condition is met */}
      {hasNotifications && <span className="badge">New Alerts!</span>}
    </div>
  );
}

Common Pitfalls

  • The Zero (0) Trap with Logical AND (&&): If you write {array.length && <List />} and the array is empty (length is 0), React will actually render the number '0' on the screen! This is because in JS, 0 is falsy, so the && short-circuits and returns 0. To fix this, always make the left side a strict boolean: {array.length > 0 && <List />}.

Interview Questions

Why can't you use a standard 'if' statement directly inside the JSX of a return block?

JSX is syntactic sugar that compiles into function calls (React.createElement()). You cannot place a block-level if statement inside a function argument in JavaScript. However, you can use expressions like ternaries (? :) because they evaluate to a specific value that can be passed as an argument.

How do you prevent a component from rendering entirely?

You can return null from the component. If a component returns null, React simply ignores it and renders nothing to the DOM for that specific branch of the tree.

Real-World Example

Data Fetching State UI: This is the exact pattern used in every production application. Early returns cleanly handle loading and error states at the top of the file, while ternaries and logical ANDs handle granular UI toggles within the main layout.

example
jsx
function Dashboard() {
  const { data, isLoading, error } = useFetchData('/api/stats');

  // 1. Error state (Early return)
  if (error) {
    return <div className="error-banner">Critical Error: {error.message}</div>;
  }

  // 2. Loading state (Early return)
  if (isLoading) {
    return <Spinner className="w-8 h-8 animate-spin" />;
  }

  // 3. Success state
  return (
    <main>
      <h1>Dashboard Analytics</h1>
      {/* Only render the premium chart if the user is a pro tier */}
      {data.isProUser && <PremiumChart data={data.charts} />}
      
      {/* Ternary for empty states */}
      {data.transactions.length > 0 
        ? <TransactionTable rows={data.transactions} />
        : <p className="text-gray-500">No transactions found this month.</p>
      }
    </main>
  );
}

Check Your Knowledge

Test your understanding of Conditional Rendering with these quick questions.

Question 1

Which operator is best used when you want to render a component if a condition is true, but render NOTHING if it is false?

Question 2

What happens if you evaluate `{ 0 && <Component /> }` inside JSX?

Take React Quiz

React.js coding notes for Indian students — 53 topics with syntax, pitfalls, interview Q&A, and inline quizzes.

Topics in React.js

  1. React Introduction
  2. Setup & Vite
  3. JSX Syntax
  4. Virtual DOM
  5. Function Components
  6. Component Tree
  7. React Fragments
  8. Passing Props
  9. Destructuring Props
  10. Children Prop
  11. Conditional Rendering
  12. List Rendering
  13. React Keys
  14. CSS Modules
  15. Event Handling
  16. Synthetic Events
  17. State Basics
  18. useState Hook
  19. State Batching
  20. Object State
  21. Array State
  22. useEffect Hook
  23. Dependency Array
  24. Cleanup Functions
  25. Data Fetching
  26. Strict Mode
  27. useRef Hook
  28. Passing Refs (forwardRef)
  29. useReducer Hook
  30. Custom Hooks
  31. useId Hook
  32. Prop Drilling Problem
  33. Context API
  34. useContext Hook
  35. Redux Intro
  36. Zustand Alternative
  37. React Router DOM
  38. Route Parameters
  39. Nested Routes
  40. Controlled Inputs
  41. React Hook Form
  42. React.memo
  43. useMemo Hook
  44. useCallback Hook
  45. Code Splitting (lazy)
  46. Bundle Size Optimization
  47. React Server Components
  48. Client Components
  49. Suspense for Data Fetching
  50. Next.js App Router
  51. Server Actions
  52. useTransition Hook
  53. React 19 Forms (useActionState)

Study next

  • All coding notes
  • React.js notes home
  • React certification quiz
  • Online compiler
  • Interview Q&A

React.js coding notes for Indian students — 53 topics with syntax, pitfalls, interview Q&A, and inline quizzes.

Topics in React.js

  1. React Introduction
  2. Setup & Vite
  3. JSX Syntax
  4. Virtual DOM
  5. Function Components
  6. Component Tree
  7. React Fragments
  8. Passing Props
  9. Destructuring Props
  10. Children Prop
  11. Conditional Rendering
  12. List Rendering
  13. React Keys
  14. CSS Modules
  15. Event Handling
  16. Synthetic Events
  17. State Basics
  18. useState Hook
  19. State Batching
  20. Object State
  21. Array State
  22. useEffect Hook
  23. Dependency Array
  24. Cleanup Functions
  25. Data Fetching
  26. Strict Mode
  27. useRef Hook
  28. Passing Refs (forwardRef)
  29. useReducer Hook
  30. Custom Hooks
  31. useId Hook
  32. Prop Drilling Problem
  33. Context API
  34. useContext Hook
  35. Redux Intro
  36. Zustand Alternative
  37. React Router DOM
  38. Route Parameters
  39. Nested Routes
  40. Controlled Inputs
  41. React Hook Form
  42. React.memo
  43. useMemo Hook
  44. useCallback Hook
  45. Code Splitting (lazy)
  46. Bundle Size Optimization
  47. React Server Components
  48. Client Components
  49. Suspense for Data Fetching
  50. Next.js App Router
  51. Server Actions
  52. useTransition Hook
  53. React 19 Forms (useActionState)

Study next

  • All coding notes
  • React.js notes home
  • React certification quiz
  • Online compiler
  • Interview Q&A