2.6K Views

REACT108 - Conditional Rendering

Learn how to render different UI states in React using conditions such as if statements, ternary operators, logical operators, and early returns.

Conditional rendering allows React applications to display different UI based on state or props.
In this lesson, you will learn the most common and recommended patterns for rendering UI conditionally in React.

What Is Conditional Rendering?

Conditional rendering means showing or hiding parts of the UI depending on a condition.

Examples include:

  • Showing a login button only when the user is logged out
  • Displaying a loading spinner while data is being fetched
  • Rendering error messages when something fails

React uses standard JavaScript logic for conditional rendering.


Using if Statements

You can use if statements outside JSX to control what gets rendered.

function Status({ isLoggedIn }) {
  if (isLoggedIn) {
    return <p>Welcome back</p>;
  }
 
  return <p>Please log in</p>;
}

This approach is clear and readable for simple conditions.


Early Return Pattern

Returning early helps avoid deeply nested JSX.

function Message({ error }) {
  if (error) {
    return <p>Something went wrong</p>;
  }
 
  return <p>Everything looks good</p>;
}

Early returns improve code clarity.


Ternary Operator

The ternary operator is commonly used inside JSX.

function AuthMessage({ isLoggedIn }) {
  return (
    <p>{isLoggedIn ? "Welcome" : "Please log in"}</p>
  );
}

Use ternaries for simple conditions only.


Logical AND Operator ( && )

The logical AND operator renders content only when the condition is true.

function Notification({ hasMessage }) {
  return (
    <div>
      {hasMessage && <p>You have a new message</p>}
    </div>
  );
}

If the condition is false, nothing is rendered.


Conditional Rendering with State

Conditional rendering is often driven by state.

function Loader() {
  const [loading, setLoading] = useState(true);
 
  return (
    <div>
      {loading ? <p>Loading...</p> : <p>Data loaded</p>}
    </div>
  );
}

This pattern is common in data-driven applications.


Avoiding Common Mistakes

Common mistakes include:

  • Using if statements directly inside JSX
  • Overusing nested ternary operators
  • Forgetting to handle all UI states

Always consider:

  • Loading state
  • Error state
  • Empty state

Conditional Rendering with Components

You can conditionally render entire components.

function App({ showModal }) {
  return (
    <div>
      {showModal && <Modal />}
    </div>
  );
}

This keeps your UI modular and clean.


Summary

In this lesson, you learned:

  • What conditional rendering is
  • Using if statements and early returns
  • Ternary operator usage
  • Logical AND rendering
  • Conditional rendering with state
  • Common pitfalls to avoid

In the next lesson, we will explore rendering lists and keys and learn how to display dynamic collections of data in React.