Conditional Rendering Using React
Code Playground is only enabled on larger screen sizes.
Sometimes you need to conditionally render a UI component according to certain logic. For instance, in the previous lesson, we already demonstrated how to accomplish something like this using if else
statements.
function App() {
const isActive = true;
if (isActive) {
return <p>Status: active</p>;
} else {
return <p>Status: inactive</p>;
}
}
export default App;
In this example, different UI will be returned based on the truthiness of isActive
. However, as you can see, there are still some repetitive code in this example, and that means we can probably simplify this somehow.
For example, instead of conditionally returning JSX, we can conditionally assign values to variables, and then embed that variable inside the JSX.
function App() {
const isActive = true;
let status;
if (isActive) {
status = "active";
} else {
status = "inactive";
}
return <p>Status: {status}</p>;
}
export default App;
We can further simplify the syntax using the conditional operator (A ? X : Y
).
function App() {
const isActive = false;
return <p>Status: {isActive ? "active" : "inactive"}</p>;
}
export default App;
In practice, we often encounter situations where an UI component is rendered when a condition is true, and nothing is rendered otherwise.
In this case, you can either return an empty tag (<></>
) or null
:
function App() {
const isActive = true;
// return <p>User: John Doe {isActive ? "✅" : <></>}</p>;
return <p>User: John Doe {isActive ? "✅" : null}</p>;
}
export default App;
In this example, a green check mark will be displayed next to the user name only if the user is active
.
However, this method is rarely used as it is logically redundant. Alternatively, you can use the logical AND operator (&&
).
function App() {
const name = "John Doe";
const isActive = true;
return (
<p>
User: {name} {isActive && "✅"}
</p>
);
}
export default App;