0
0
ReactHow-ToBeginner · 3 min read

How to Render Component Conditionally in React: Simple Guide

In React, you can render components conditionally using JavaScript expressions inside JSX. Common ways include using if statements, the ternary operator, or the logical && operator to decide which component or element to show based on a condition.
📐

Syntax

Conditional rendering in React uses JavaScript expressions inside JSX to decide what to show. Here are common patterns:

  • If statement: Use outside JSX to choose what to return.
  • Ternary operator: Inline expression condition ? true : false inside JSX.
  • Logical AND (&&): Render component only if condition is true.
jsx
function Greeting({ isLoggedIn }) {
  if (isLoggedIn) {
    return <h1>Welcome back!</h1>;
  } else {
    return <h1>Please sign up.</h1>;
  }
}

// Using ternary operator
const message = isLoggedIn ? <h1>Welcome back!</h1> : <h1>Please sign up.</h1>;

// Using logical &&
const message2 = isLoggedIn && <h1>Welcome back!</h1>;
💻

Example

This example shows a React component that displays a greeting message based on whether the user is logged in or not. It uses the ternary operator inside JSX for clear and concise conditional rendering.

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

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

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

export default Greeting;
Output
When isLoggedIn is false: Displays 'Please sign up.' and a 'Login' button. When button clicked, isLoggedIn becomes true: Displays 'Welcome back!' and a 'Logout' button.
⚠️

Common Pitfalls

Some common mistakes when rendering conditionally in React include:

  • Trying to use if statements directly inside JSX, which is invalid syntax.
  • Returning null or false unintentionally, which renders nothing but might confuse beginners.
  • Using the logical AND (&&) operator when the left side can be a value that React renders (like 0), causing unexpected output.
jsx
function WrongExample({ count }) {
  // This will render 0 if count is 0, which shows on screen
  return <div>{count && <p>Count is {count}</p>}</div>;
}

function RightExample({ count }) {
  // Check explicitly for count > 0
  return <div>{count > 0 && <p>Count is {count}</p>}</div>;
}
📊

Quick Reference

Here is a quick summary of conditional rendering methods in React:

MethodUsageWhen to Use
If statementUse outside JSX to return different componentsComplex conditions or multiple returns
Ternary operatorcondition ? A : B inside JSXSimple two-way choices
Logical AND (&&)condition && A inside JSXRender something only if condition is true

Key Takeaways

Use JavaScript expressions inside JSX to render components conditionally.
Prefer ternary operators for simple two-choice rendering inside JSX.
Use if statements outside JSX for more complex conditional logic.
Be careful with logical && to avoid rendering unwanted values like 0.
Always test your conditions to ensure the UI behaves as expected.