Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 3.1 — Conditional Rendering
React · Example 2 of 3

The 0 && gotcha

The first box shows a lonely 0. The fix is a real comparison on the left of &&.

Conditional rendering means a component shows different UI for different data, using plain JavaScript: an if with an early return, the ternary ? :, &&, returning null, conditional props and classes, and picking a component from a variable or an object map.

Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.

Ready for more? This phase has 5 hands-on exercises with automatic checks.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Write a Status component that takes an online boolean and shows a green Online or a grey Offline label, using a ternary for both the text and the class.

02

Write a Notifications component that takes count and shows You have N new notifications only when count is above zero, and null otherwise. Make sure count = 0 shows nothing at all.

03

Write a Weather component that takes kind ("sun", "rain" or "snow") and renders <Sun />, <Rain /> or <Snow /> using an object map, with a fallback <p>Unknown weather</p> for any other value.

Explain it without notes

01

Why can't you write if directly inside JSX curly braces, and what do you use instead?

02

Explain the 0 && bug and two ways to fix it.

03

What happens when a component returns null? How is that different from not rendering it in the parent?

04

How do you choose between many components without a long chain of ternaries?

05

How do you make an attribute or a class conditional, and how do you leave an attribute out completely?

The 0 && gotcha

Preview

Press Run to see the page.

Console

Nothing logged yet.

Expected console output

Cart shows: "0"
FixedCart shows: ""