Ternary Rendering
Part of the Fundamentals section of Coddy's React journey. Lesson 33 of 42.
JSX braces can't hold an if statement, but they hold the ternary operator perfectly, and it covers almost every either/or on a screen:
{isLoggedIn ? 'Welcome back!' : 'Please log in'}Condition first, then the value for true, then the value for false. Both sides can be full JSX elements:
{isLoggedIn
? <p>Welcome back!</p>
: <button>Log in</button>}Pair it with state and the page switches live: flip the boolean, React re-renders the other branch.
Challenge
EasyBuild a login status line.
- Add boolean state
loggedIn, startingfalse. - The button (
id="login") flips it on every click. - The paragraph (
id="status") showsWelcome back!when logged in andPlease log inotherwise, with a ternary.
Try it yourself
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="styles.css" />
</head>
<body>
<div id="root"></div>
<script type="module" src="main.jsx"></script>
</body>
</html>This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
7Conditions & Lists
Ternary RenderingShow with &&Render a ListKeys MatterFilter, Then MapRecap: Conditions & Lists2JSX Expressions
Curly BracesMath in BracesBraces in AttributesCalling Functions in JSXRecap: JSX Expressions5State & Events
What Is State?Click CounterCount in StepsToggle with StateIndependent StateRecap: State & Events8Project: Profile Card
Step 1: Card StructureStep 2: Card with PropsStep 3: Like ButtonStep 4: Follow Toggle