Loading course content...
Loading course content...
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 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 some repetitive code in this example, and that means we can probably simplify this.
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 only rendered when a condition is true.
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.
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;export default function App() { return <h1>Hello, World!</h1> }