Conditional Rendering in React

Learn how to render different UI elements dynamically based on conditions in React.

1. What is Conditional Rendering?

Conditional rendering in React allows you to dynamically render UI elements based on certain conditions or states. It works similarly to JavaScript conditional statements such as if and ternary operators.

2. Using if/else Statements

The simplest way to implement conditional rendering is by using if/else statements.

function WelcomeMessage({ isLoggedIn }) {
    if (isLoggedIn) {
        return 

Welcome back!

; } else { return

Please log in.

; } }

Explanation: The UI displays a different message based on the value of isLoggedIn.

3. Using Ternary Operators

A concise way to conditionally render elements is with ternary operators:

function Greeting({ isLoggedIn }) {
    return (
        

{isLoggedIn ? "Welcome back!" : "Please log in."}

); }

Explanation: The ternary operator determines which string is displayed based on the isLoggedIn value.

4. Using Logical && Operators

To conditionally render elements without an else block, you can use the logical && operator:

function Notifications({ hasNotifications }) {
    return (
        

Dashboard

{hasNotifications &&

You have new notifications!

}
); }

Explanation: The && operator ensures the paragraph is rendered only if hasNotifications is true.

5. Inline Conditional Rendering

Inline rendering is useful for small conditional expressions:

function InlineExample({ isAdmin }) {
    return (
        

{isAdmin ? "Admin Access Granted" : "User Access Only"}

); }

Explanation: The paragraph displays different messages based on the isAdmin value.

6. Best Practices

  • Keep conditional logic simple to maintain readability.
  • Use separate functions or variables for complex logic.
  • Avoid deeply nested conditionals for better performance and code clarity.

Additional Resources