React: From Components to Production · Components and JSX
Lists, Keys and Conditional Rendering
Render collections correctly and show UI conditionally.
Render lists with array.map() and give each item a stable, unique key (usually a database ID). Keys tell React which items moved, were added or removed, so state stays attached to the right item. Use if/early returns, ternaries and && for conditional UI, and handle loading, empty and error states explicitly.
type Todo = { id: string; title: string; done: boolean };
export function TodoList({ todos }: { todos: Todo[] }) {
if (todos.length === 0) {
return <p className="empty">Nothing to do</p>;
}
return (
<ul>
{todos.map((todo) => (
<li key={todo.id} className={todo.done ? "done" : undefined}>
{todo.title}
</li>
))}
</ul>
);
}
export function TodoList({ todos }) {
if (todos.length === 0) {
return <p className="empty">Nothing to do</p>;
}
return (
<ul>
{todos.map((todo) => (
<li key={todo.id} className={todo.done ? "done" : undefined}>
{todo.title}
</li>
))}
</ul>
);
}
Common pitfalls
- Using array indexes as keys for lists that reorder or change — state gets attached to the wrong items.
- Generating keys with
Math.random()(remounts every render). - Forgetting empty and loading states.
Key points
- Stable unique keys, not indexes
- Early returns for special states
- Design empty/loading/error states
Further reading: react.dev: Rendering lists
Practice questions
Why are array indexes bad keys for a sortable list?
Answer
When items reorder, indexes stay the same while content changes, so React reuses component state (like input values) for the wrong items.
Can you use a key to reset a component's state?
Answer
Yes. Changing the key prop makes React treat it as a new component, unmounting the old one and mounting a fresh instance with initial state.
Open in the app to mark lessons complete, take notes and track your progress.