Sub topic 3
Showing or Hiding with `&&` and the `0` Pitfall
Assume you know JavaScript arrays, objects, map, and filter. You should also know React components, props, JSX, and the useState hook.
Showing or hiding with `&&`
In JSX, condition && content renders content only when condition is truthy. Otherwise, React renders nothing.
function Inbox({ unreadCount }) {
return (
<div>
{unreadCount > 0 && (
<span>{unreadCount} unread messages</span>
)}
</div>
);
}Be careful with numbers. JavaScript treats 0 as falsy, but React renders the left side of && when it is a number. Therefore, unreadCount && <span>...</span> displays 0 when the count is zero. Compare the number with 0 first to produce a Boolean result.
Rendering nothing with `null`
A component can return null when it should produce no UI.
function AdminTools({ isAdmin }) {
if (!isAdmin) {
return null;
}
return <button>Manage users</button>;
}Returning null is different from returning an empty element. React keeps the component in the tree but places no DOM elements on the page.
Handling empty lists
Check for an empty array before rendering its items. An empty state tells users what happened and what they can do next.
function Results({ results }) {
if (results.length === 0) {
return <p>No results found.</p>;
}
return (
<ul>
{results.map(result => (
<li key={result.id}>{result.title}</li>
))}
</ul>
);
}Updating list state immutably
When changing state, create a new array instead of modifying the existing one. filter removes an item, while spread syntax adds one.
const [tasks, setTasks] = useState([]);
function addTask(task) {
setTasks(previous => [...previous, task]);
}
function removeTask(id) {
setTasks(previous => previous.filter(task => task.id !== id));
}For an edit, use map and replace only the matching object.
setTasks(previous =>
previous.map(task =>
task.id === id ? { ...task, done: !task.done } : task
)
);Resetting state with a key
React preserves a component's state while it keeps the same identity. Give a component a different key when a new identity should start with fresh state.
function ProfilePage({ userId }) {
return <Profile key={userId} userId={userId} />;
}When userId changes, React discards the old Profile state and creates a new instance.
Exercise
Why does count > 0 && <p>...</p> avoid the zero pitfall?
Show answer
The comparison returns true or false, so React receives false when count is zero instead of the number 0.