DEV Community

Kazutora Hattori
Kazutora Hattori

Posted on

[Introduction to React] Summary of conditional rendering: How to smartly switch visibility

Introduction

In React, you often need to "display only under certain conditions" or "change the display content depending on the situation." The technique for achieving this is called conditional rendering.

This article summarizes the most common ways to do this.

  1. Using the AND Operator (&&)

Use this when you want to display something only when a condition is true.

function App() {
const isLoggedIn = true;
return (
<div>
{isLoggedIn && <p>Welcome!</p>}
</div>
);
}
Enter fullscreen mode Exit fullscreen mode

If isLoggedIn is true →

Welcome!

is displayed.

If it is false → Nothing is displayed.

2. Using the Ternary Operator (? :)

This is useful when you want to switch the display between true and false.

function App() {
const isLoggedIn = false;
return (
<div>
{isLoggedIn ? <p>Welcome!</p> : <p>Please log in</p>}
</div>
);
}
Enter fullscreen mode Exit fullscreen mode

If true → Display "Welcome!"

If false → Display "Please log in."

3. Use the null coalescing operator (??)

This is useful in cases where you want to display a fallback (alternative text) only when the value is undefined or null.

function App() {
const userName = null;
return (
<div>
<p>{userName ?? "Guest"}</p>
</div>
);
}
Enter fullscreen mode Exit fullscreen mode

userName is "Ken" → Display "Ken" (userName has a value)

userName is null or undefined → Display "Guest"

4. Use an if statement (branching within JavaScript logic)

When using complex conditional branching or multiple patterns, using JavaScript's if statement is easier to read.

function App() {
const role = "admin";
let content;

if (role === "admin") {
content = <p>Admin Page</p>;
} else if (role === "user") {
content = <p>User Page</p>;
} else {
content = <p>Guest Page</p>;
}

return <div>{content}</div>;
}
Enter fullscreen mode Exit fullscreen mode

5. Separate Components and Call Them Conditionally

If your logic is long, you can separate it into components to make it easier to read.

function Admin() {
return <p>Admin Page</p>;
}

function User() {
return <p>User Page</p>;
}

function App() {
const role = "user";
return (
<div>
{role === "admin" ? <Admin /> : <User />}
</div>
);
}
Enter fullscreen mode Exit fullscreen mode

Summary

There are several patterns for conditional rendering in React.

  • && → Display only if true

  • Ternary operator → Display true/false

  • ?? → Display an alternative value if the value is null/undefined

  • if statement → Strong for branching between multiple conditions

  • Component division → Increased readability and reusability

Using these methods appropriately will make your code clearer and easier to read.

Top comments (0)