Pick a component from an object map
The buttons get a conditional class and aria-pressed, and VIEWS[mode] picks which component renders. Try adding a fourth view.
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.
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.
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.
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
Why can't you write if directly inside JSX curly braces, and what do you use instead?
Explain the 0 && bug and two ways to fix it.
What happens when a component returns null? How is that different from not rendering it in the parent?
How do you choose between many components without a long chain of ternaries?
How do you make an attribute or a class conditional, and how do you leave an attribute out completely?
Preview
Console
Nothing logged yet.