ReactBeginner

Project 1: Build a To-Do List App in React

Build a complete React to-do app step by step: components, props, state, forms, lists, filters and events, with every file explained.

React CourseLesson 16 of 66 (24% complete)
All React lessons (66)View curriculum

What you will build

You have learned components, props, lists, conditional rendering, events, state, and forms. Now you will put them all together in one real application: a to-do list. It is a classic first project because it uses almost every beginner skill, and you will actually use the result.

Your finished app will let you:

  • Add a task with a form (empty tasks are ignored).
  • Tick a task as done, or untick it.
  • Delete a task.
  • See how many tasks are left.
  • Filter the list: all, active or done.
  • Clear all completed tasks with one button.

Here is what the finished page looks like in text form:

My Tasks

New task  [ What needs to be done?        ] [Add]

[x] Learn JSX                    [Delete]
[x] Learn props                  [Delete]
[ ] Build a to-do app            [Delete]

1 task left     [all] [active] [done]     [Clear completed]

You need a working Vite React project (see setting up React with Vite) with the clean App.jsx from the project structure lesson.

Which skills does this project use?

Skill Lesson
Function components and imports First component
Passing data and functions down Props
Lists and keys Lists and keys
Showing an empty message Conditional rendering
Click and submit handlers Events
useState useState
Add, edit, delete items immutably Updating state
Controlled input and submit Forms

Step 1: plan before you code

Good developers plan the component tree and decide where each piece of state lives before writing code. Our plan:

App                     owns the list of todos and the current filter
├── TodoForm            owns only the text being typed
├── TodoList            shows the visible todos
│   └── TodoItem        shows one todo (checkbox, title, delete button)
└── TodoFooter          shows the count, the filter buttons and "Clear completed"

Todo app component tree

Now think about the data. A single todo is an object:

{ id: 1, title: "Learn JSX", done: true }

Why an id? Each todo needs a stable, unique key for the list, and a way to say which todo to toggle or delete. We will not use the array index for that, because the list changes.

Who owns which state?

State Owner Why
todos (the array) App TodoList, TodoFooter and the handlers all need it
filter ("all", "active", "done") App The footer changes it, and the list depends on it
title (text in the input) TodoForm Nobody else needs it, so it stays local

Notice the rule we are following: keep state as close as possible to where it is used, but high enough that every component that needs it can reach it. The next lessons will explain this idea in depth.

We do not store the number of remaining tasks or the filtered list in state. We calculate them from todos and filter on every render. That avoids bugs where two values get out of sync.

Step 2: create the files

Inside src, create a folder components. Your project will have these files:

src/
├── components/
│   ├── TodoForm.jsx
│   ├── TodoFooter.jsx
│   ├── TodoItem.jsx
│   └── TodoList.jsx
├── App.css        (replace the starter content)
├── App.jsx        (replace)
├── index.css
└── main.jsx

We build from the smallest piece upward.

Step 3: TodoItem, one task

src/components/TodoItem.jsx:

function TodoItem({ todo, onToggle, onDelete }) {
  return (
    <li className={todo.done ? "todo-item todo-item--done" : "todo-item"}>
      <label>
        <input type="checkbox" checked={todo.done} onChange={() => onToggle(todo.id)} />
        <span>{todo.title}</span>
      </label>
      <button type="button" onClick={() => onDelete(todo.id)} aria-label={`Delete ${todo.title}`}>
        Delete
      </button>
    </li>
  );
}

export default TodoItem;

What happens here:

  • The component receives one todo and two function props: onToggle and onDelete. It does not change any data itself. It only reports what the user did. (This is the “events as props” pattern from the events lesson.)
  • The className uses a ternary, so finished tasks get an extra class todo-item--done for styling.
  • The checkbox is controlled: checked={todo.done}. When it changes, we call onToggle(todo.id) so the parent can update the data.
  • Wrapping the checkbox and text in a <label> means clicking the text also toggles the box.
  • aria-label gives screen readers a clear name for each Delete button, such as Delete Learn JSX. Without it, every button would just say “Delete”.

Step 4: TodoList, the list

src/components/TodoList.jsx:

import TodoItem from './TodoItem.jsx';

function TodoList({ todos, onToggle, onDelete }) {
  if (todos.length === 0) {
    return <p className="empty">Nothing to show here.</p>;
  }

  return (
    <ul className="todo-list">
      {todos.map((todo) => (
        <TodoItem key={todo.id} todo={todo} onToggle={onToggle} onDelete={onDelete} />
      ))}
    </ul>
  );
}

export default TodoList;
  • If there are no todos to show, it returns a friendly message (an early return, from the conditional rendering lesson).
  • Otherwise it maps each todo to a TodoItem, with key={todo.id}.
  • It simply passes the two handlers down to each item.

Step 5: TodoForm, adding a task

src/components/TodoForm.jsx:

import { useState } from 'react';

function TodoForm({ onAdd }) {
  const [title, setTitle] = useState("");

  function handleSubmit(event) {
    event.preventDefault();
    const trimmed = title.trim();
    if (trimmed === "") {
      return;
    }
    onAdd(trimmed);
    setTitle("");
  }

  return (
    <form onSubmit={handleSubmit} className="todo-form">
      <label htmlFor="new-task">New task</label>
      <input
        id="new-task"
        type="text"
        value={title}
        onChange={(event) => setTitle(event.target.value)}
        placeholder="What needs to be done?"
      />
      <button type="submit">Add</button>
    </form>
  );
}

export default TodoForm;

This is a controlled input (see the forms lesson):

  • The text being typed lives in this component’s own state, title.
  • On submit, event.preventDefault() stops the page reload.
  • title.trim() removes spaces from both ends. If nothing is left, the function returns early, so empty and blank tasks are ignored.
  • onAdd(trimmed) hands the new title to the parent. The form does not know where todos are stored.
  • setTitle("") clears the input for the next task.

Step 6: TodoFooter, count, filters and clear

src/components/TodoFooter.jsx:

const filters = ["all", "active", "done"];

function TodoFooter({ remaining, hasCompleted, filter, onFilterChange, onClearCompleted }) {
  return (
    <footer className="todo-footer">
      <p>{remaining} {remaining === 1 ? "task" : "tasks"} left</p>
      <div>
        {filters.map((name) => (
          <button
            key={name}
            type="button"
            onClick={() => onFilterChange(name)}
            aria-pressed={filter === name}
          >
            {name}
          </button>
        ))}
      </div>
      {hasCompleted && (
        <button type="button" onClick={onClearCompleted}>Clear completed</button>
      )}
    </footer>
  );
}

export default TodoFooter;
  • The filters array lives outside the component, because it never changes. Each filter button is created with map(), with the filter name as the key.
  • aria-pressed={filter === name} tells assistive technology which filter is active, and you can also use it in CSS.
  • The ternary remaining === 1 ? "task" : "tasks" gets the grammar right (1 task left, 2 tasks left).
  • The Clear completed button uses &&, so it only appears when at least one task is done.
  • This component is purely presentational: it gets everything through props and owns no state.

Step 7: App, where it all connects

Replace src/App.jsx with:

import { useState } from 'react';
import './App.css';
import TodoForm from './components/TodoForm.jsx';
import TodoList from './components/TodoList.jsx';
import TodoFooter from './components/TodoFooter.jsx';

let nextId = 4;

const initialTodos = [
  { id: 1, title: "Learn JSX", done: true },
  { id: 2, title: "Learn props", done: true },
  { id: 3, title: "Build a to-do app", done: false },
];

function App() {
  const [todos, setTodos] = useState(initialTodos);
  const [filter, setFilter] = useState("all");

  function addTodo(title) {
    setTodos([...todos, { id: nextId++, title, done: false }]);
  }

  function toggleTodo(id) {
    setTodos(todos.map((todo) => todo.id === id ? { ...todo, done: !todo.done } : todo));
  }

  function deleteTodo(id) {
    setTodos(todos.filter((todo) => todo.id !== id));
  }

  function clearCompleted() {
    setTodos(todos.filter((todo) => !todo.done));
  }

  const visibleTodos = todos.filter((todo) => {
    if (filter === "active") return !todo.done;
    if (filter === "done") return todo.done;
    return true;
  });
  const remaining = todos.filter((todo) => !todo.done).length;

  return (
    <main className="todo-app">
      <h1>My Tasks</h1>
      <TodoForm onAdd={addTodo} />
      <TodoList todos={visibleTodos} onToggle={toggleTodo} onDelete={deleteTodo} />
      <TodoFooter
        remaining={remaining}
        hasCompleted={todos.length > remaining}
        filter={filter}
        onFilterChange={setFilter}
        onClearCompleted={clearCompleted}
      />
    </main>
  );
}

export default App;

This is the brain of the app. Let us go through it:

  • Two pieces of state: todos and filter.
  • nextId is a plain variable outside the component. It gives each new task a unique id (4, 5, 6…). It is only changed inside the addTodo event handler, never during rendering.
  • Four handlers, each using an update pattern from the state updating lesson:
    • addTodo: a new array with the old todos plus one new one ([...todos, newTodo]).
    • toggleTodo: map() returns a new object only for the matching todo and leaves the others unchanged.
    • deleteTodo and clearCompleted: filter() keeps only the todos we want.
  • Calculated values: visibleTodos (depends on filter) and remaining are computed on every render. They are not state.
  • hasCompleted={todos.length > remaining} is a quick way to ask “is there any done task?”: if the total is bigger than the number left, some tasks are done.
  • The JSX passes data and handlers down as props. Notice onFilterChange={setFilter}: a state setter is just a function, so you can pass it directly.

Step 8: styling

Replace the content of src/App.css with:

.todo-app {
  max-width: 480px;
  margin: 0 auto;
  padding: 24px 16px;
  text-align: left;
}

.todo-form {
  display: grid;
  gap: 8px;
  margin-bottom: 16px;
}

.todo-form input {
  padding: 8px 12px;
  font-size: 1rem;
}

.todo-list {
  list-style: none;
  margin: 0;
  padding: 0;
}

.todo-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 12px;
  padding: 8px 0;
  border-bottom: 1px solid #ccc;
}

.todo-item--done span {
  text-decoration: line-through;
  opacity: 0.6;
}

.todo-footer {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  justify-content: space-between;
  gap: 8px;
  margin-top: 16px;
}

.todo-footer button[aria-pressed="true"] {
  font-weight: 700;
  text-decoration: underline;
}

.empty {
  padding: 16px 0;
  opacity: 0.7;
}

Because App.jsx imports ./App.css, Vite loads it. The selector button[aria-pressed="true"] styles the active filter, using the attribute we set in the footer. (This CSS uses ideas from the flexbox lessons and attribute selectors.)

Try your app

Run npm run dev and test each feature in order. This is what you should see:

  1. At the start: three tasks, two ticked, and 1 task left.
  2. Add a task: type Write tests and press Enter or click Add. The task appears at the bottom, the input is cleared, and the footer says 2 tasks left. Submitting an empty or blank field does nothing.
  3. Toggle: tick Build a to-do app. It gets a line through it, and the footer says 1 task left.
  4. Filter: click active. Only unfinished tasks remain. Click done to see only finished ones. Click all to see everything.
  5. Clear completed: click it (the button only exists while something is done). All ticked tasks disappear.
  6. Empty message: with the done filter active and nothing done, you see Nothing to show here.
  7. Delete: click Delete on any task. It disappears and the count updates.

How the data flows

Here is the whole app in one picture. This is the most important idea of the project:

              ┌───────────── App ─────────────┐
              │ state: todos, filter           │
              │ handlers: add, toggle, delete  │
              └──────┬─────────────┬───────────┘
        props down   │             │   props down
                     ▼             ▼
               TodoList        TodoFooter
                     │
                     ▼
                TodoItem
                     │
   user clicks ─────►│  onToggle(id)  ──► App.toggleTodo ──► setTodos ──► re-render

Data flows down as props. Events flow up as function calls. Every change goes through App, so there is only one place where the list can change. This makes the app easy to reason about and easy to debug.

Common mistakes

1. Mutating the todos array. Writing todos.push(newTodo) or todo.done = true and then calling setTodos(todos) will not update the screen. Create new arrays and objects.

2. Using the index as the key. With filtering and deleting, indexes change, so React can mix up rows. Use todo.id.

3. Storing derived data in state. Do not add useState for remaining or visibleTodos. Calculate them.

4. Forgetting event.preventDefault(). The page reloads when you add a task, and everything resets.

5. Calling the handler immediately. onClick={onDelete(todo.id)} runs during rendering. Use onClick={() => onDelete(todo.id)}.

6. Putting onSubmit on the button. Put it on the <form> so the Enter key works too.

7. Forgetting to clear the input. After adding, call setTitle("").

8. Giving two todos the same id. The next id must always be new. nextId++ takes care of this.

Practice (extend the project)

  1. Show a task counter in the page title area: 3 tasks in total. Calculate it from todos.

  2. Add a Mark all as done button to the footer. It should set done: true on every todo using map().

  3. Predict, then check: What happens if you change key={todo.id} to key={Math.random()} in TodoList? Test it with the keyboard: press Tab to focus a checkbox, press Space to tick it, and watch whether the focus stays on that checkbox. Then change the key back.

  4. Prevent duplicate titles: in addTodo, do nothing if a task with the same title (ignoring capital letters) already exists.

  5. Add a priority field to each todo ("low", "normal", "high") and show it next to the title. Use a select in TodoForm to choose it.

  6. Debug: A learner wrote this toggleTodo. Ticking a task does nothing on screen. Why, and how do you fix it?

    function toggleTodo(id) {
      const todo = todos.find((todo) => todo.id === id);
      todo.done = !todo.done;
      setTodos(todos);
    }
  7. Add an Edit feature: clicking a task’s title turns it into an input. (Hint: TodoItem can keep its own isEditing state.)

  8. Style the high priority tasks with a red left border using a dynamic class name.

Recap

  • You built a complete app with five components and two pieces of state.
  • Plan first: draw the component tree and decide who owns each piece of state.
  • Data flows down as props, events flow up as function props. All changes go through App.
  • Update arrays by creating new ones: [...todos, item], map() and filter().
  • Calculate the filtered list and the count instead of storing them.
  • Keep small, local state (the text in the input) inside the component that needs it.
  • Next you will study this “who owns the state” question properly, in the lesson on lifting state up.

Frequently asked questions

Why is the todos state in App and not in TodoList?

Because several components need it: TodoList shows it, TodoFooter counts it, and the handlers change it. State must live in the closest component that is a parent of everything that needs it. That is App.

Why is title state inside TodoForm?

Only the form cares about the text being typed. The rest of the app only needs the finished title, which the form sends up with onAdd. Keeping state local when possible makes components simpler and easier to reuse.

Will my tasks disappear when I refresh the page?

Yes. State lives in memory, so a refresh resets it to initialTodos. You can save tasks in localStorage (see the storage lesson). The custom Hooks lesson shows how to do this cleanly in React, and you will upgrade this very app.

Why is nextId outside the component?

A variable inside the component would be created again on every render and reset to 4. Outside, it keeps its value. It is only changed in an event handler, which is allowed. For a real app, ids usually come from a database or from crypto.randomUUID().

Is it fine that every component is in a separate file?

Yes, that is the common convention: one component per file, named after the component. It keeps files short and easy to find, and each file imports only what it needs.

How can I improve this app further?

Add editing, due dates, categories, drag-and-drop ordering, saving to localStorage, and later loading and saving tasks from a server. Every idea uses the same pattern you learned here: state in a parent, props down, events up.

See also: React Props, Updating Objects and Arrays in State, React Forms, JavaScript localStorage