Sub topic 1
Setting Up and Writing Your First Components
Prerequisites
Assume you know JavaScript functions, arrays, objects, map, filter, and spread syntax. You also need a React project created with Vite or a similar tool.
Components and JSX
A React component is a JavaScript function that returns JSX, a syntax that describes HTML-like elements. Start the development server with npm run dev, then replace src/App.jsx with this small to-do app:
import { useState } from "react";
function TodoItem({ todo, onToggle }) {
return (
<li>
<label>
<input
type="checkbox"
checked={todo.done}
onChange={() => onToggle(todo.id)}
/>
{todo.title}
</label>
</li>
);
}
export default function App() {
const [todos, setTodos] = useState([]);
const [text, setText] = useState("");
function addTodo(event) {
event.preventDefault();
const title = text.trim();
if (!title) return;
setTodos([
...todos,
{ id: crypto.randomUUID(), title, done: false },
]);
setText("");
}
function toggleTodo(id) {
setTodos(
todos.map((todo) =>
todo.id === id ? { ...todo, done: !todo.done } : todo
)
);
}
return (
<main>
<h1>To-do</h1>
<form onSubmit={addTodo}>
<label>
New task
<input
value={text}
onChange={(event) => setText(event.target.value)}
/>
</label>
<button type="submit">Add</button>
</form>
<ul>
{todos.map((todo) => (
<TodoItem key={todo.id} todo={todo} onToggle={toggleTodo} />
))}
</ul>
</main>
);
}Storing To-dos in State
State is data that a component owns and that can change over time. useState([]) returns the current array and a setter function. Calling setTodos asks React to render again with the new array.
The text state controls the input. This is a controlled input: its value comes from state, and onChange updates that state.
Props and Events
Props are values passed from a parent component to a child. TodoItem receives the todo object and the onToggle callback. The parent keeps ownership of state, while the child reports user actions through the callback.
onSubmit handles form submission. preventDefault() stops the browser from reloading the page. onChange handles typing, and onToggle handles checking a task.
Exercise
Why does toggleTodo create a new array instead of changing todo.done directly?
Show answer
React detects the new array reference and can render the updated list reliably.