Sub topic 3
Rendering Conditionally
Assume you know modern JavaScript, basic HTML, and ES modules. React components can choose what to return based on props or state.
Rendering conditionally
Use normal JavaScript conditions inside a component. Return early when one case needs a completely different result. For small choices, use a conditional operator or &&.
import { useState } from 'react';
const initialTodos = [
{ id: 1, text: 'Read the React guide' },
{ id: 2, text: 'Build a component' },
];
export default function TodoPanel() {
const [todos, setTodos] = useState(initialTodos);
function clearTodos() {
setTodos([]);
}
return (
<section>
<h1>Tasks</h1>
{todos.length === 0 ? (
<p>Nothing to do.</p>
) : (
<ul>
{todos.map((todo) => (
<li key={todo.id}>{todo.text}</li>
))}
</ul>
)}
<button onClick={clearTodos}>Clear tasks</button>
</section>
);
}Rendering lists and choosing keys
map converts each data item into JSX. A key is a stable identifier React uses to match an item between renders. Use a database ID or another value that stays tied to the item. Do not use an array index when items can be inserted, removed, or reordered.
Responding to events
Event attributes use camelCase, such as onClick. Pass a function, rather than calling it during rendering. In the example, clicking the button calls clearTodos.
Remembering values with useState
useState stores a value between renders. It returns the current value and a setter. Calling the setter schedules a new render. Treat state as immutable: create a new array or object instead of changing the existing value.
Keeping components pure
A pure component returns the same JSX for the same props and state. Do not modify external variables, make network requests, or change the DOM during rendering. Put user actions in event handlers and synchronization work in the appropriate effect.
Class components and why you may still see them
Class components extend React.Component and use methods such as render and this.setState. Function components with hooks are the current default, but older applications and libraries may still contain classes. You can maintain them without converting every file.
Exercise
Why is key={todo.id} safer than key={index} for an editable list?
Show answer
The stable ID stays attached to the same item when the list changes, so React preserves the correct element and its state.