Showing things conditionally
You'll learn to show different things on screen depending on a condition, with if, ? : and &&.
Watch & read
Start with the required ones. The others are there when you need them.
Explanation
You want your to-do app to say "No tasks yet." when the list is empty, and show the list when it is not. Showing different JSX depending on a condition is called conditional rendering. It is plain JavaScript, used in three ways.
1. if with an early return. Good when the whole screen changes.
if (tasks.length === 0) {return <p>No tasks yet.</p>;}return <TaskList tasks={tasks} />;
2. The ternary condition ? a : b. Good inside JSX when you want one thing or another. Read ? as
"then" and : as "else": {isOnline ? <p>Online</p> : <p>Offline</p>}.
3. &&. Good when you want something or nothing: {hasDue && <p>Fee due</p>}. If hasDue is
false, React shows nothing. You can also return null to show nothing at all.
People often put a number before &&. With {items.length && <p>...</p>} and an empty list,
items.length is 0. && gives back that 0, and React shows a 0 on the screen. Write a real
true/false check instead: {items.length > 0 && ...}.
When you read JSX, find each ? and &&, and say out loud: "if this, show that".
Code tour
Click a line number with a ring to read the note for that line.
Practice
Short drills. Take your time and read the code before you answer.
1function Cart({ items }) {2 return (3 <div>4 <h2>Cart</h2>5 {items.length && <p>{items.length} items</p>}6 </div>7 );8}910// used as <Cart items={[]} />
statusMessage to choose what to show. While loading, it must say "Loading...". If loading failed, it must say "Something went wrong.". Only when it has finished with no error and no tasks should it say "No tasks yet.". Fix the order of the checks so all four pass.Quick check
3 questions. Each one explains itself after you answer.
- 1 / 3With
isPaid = false, what does{isPaid ? <p>Paid</p> : <p>Due</p>}show? - 2 / 3With
hasDue = false, what does{hasDue && <p>Fee due</p>}show? - 3 / 3Which is the safe way to show a list only when it has items?
Explain it back
How confident are you with Showing things conditionally?
Done
&& inside JSX and say what appears for a given value, including the 0 trap.