Components and JSX · Lesson 5 of 21
Conditional rendering
if before return, the ternary, &&, and the zero trap.
7 minutes2 games
Three ways to show something based on a condition:
1. if before return, when the whole output changes (loading, error).
2. A ternary cond ? A : B inside JSX, choosing between two things.
3. cond && A to show something or nothing.
React
function CourseStatus({ progress, enrolled, newLessons }) {
if (!enrolled) {
return <p>Enroll to start learning.</p>
}
return (
<div>
<p>{progress === 100 ? "Completed ✔" : "In progress: " + progress + "%"}</p>
{newLessons > 0 && <p>{newLessons} new lessons!</p>}
</div>
)
}
function App() {
return (
<>
<CourseStatus enrolled={false} />
<hr />
<CourseStatus enrolled progress={60} newLessons={2} />
<hr />
<CourseStatus enrolled progress={100} newLessons={0} />
</>
)
}React
function App() {
const messages = []
return (
<div>
<p>Wrong: {messages.length && <b>You have mail</b>}</p>
<p>Right: {messages.length > 0 && <b>You have mail</b>}</p>
</div>
)
}What's the output?
function App() {
const items = []
const user = null
return (
<p>
{items.length && "list"}
{user && user.name}
{false}
{"!"}
</p>
)
}What will the page show?
Exercise
Finish Inbox: show No new messages for 0, 1 new message for 1, and N new messages for more. The page shows all three cases one under another.
The page should show:
No new messages 1 new message 7 new messages
React
function Inbox({ count }) {
return <p>{count}</p>
}
function App() {
return (
<div>
<Inbox count={0} />
<Inbox count={1} />
<Inbox count={7} />
</div>
)
}Learn more from
Played 0 of 2 games
Sign in to save your progress and earn XP.