Conditional Rendering
-
This lesson explains conditional rendering in React and teaches how to display content dynamically based on conditions.
Topic Overview
React allows us to display UI dynamically based on conditions and data.
Conditional Rendering and Lists are used in almost every real-world React application.Conditional Rendering
Conditional Rendering means showing different UI elements based on a condition.
In simple words:
React decides what to show based on values like state or props.if Statements in JSX
JSX does not allow if statements directly inside JSX.
❌ Not allowed:
{ if (isLoggedIn) {} }
Correct Way:
Use if statements before the return.
if (isLoggedIn) {
return <Dashboard />;
}
return <Login />;
Best for complex conditions.
Ternary Operator
The ternary operator is used for simple conditions.
Syntax:
condition ? trueUI : falseUI
- Example:
<h1>{isLoggedIn ? "Welcome" : "Please Login"}</h1>
Most commonly used method in React.
Logical AND Operator (&&)
The logical AND operator is used when UI is shown only if condition is true.
Example:
{isAdmin && <AdminPanel />}
- If isAdmin is false, nothing is rendered.