Thuta Learning
React
ProjectsWeb DevelopmentIntermediate

Project: Task Tracker Setup

ReactLesson 2935 min

What you'll walk away with

  • Decide which component owns the task list and which one only displays a single task
  • Pass task fields down as props and destructure them in the child's parameter list
  • Render the array with map() and give each item a stable key taken from task.id
  • Derive display values such as "1 of 3 done" from the data instead of storing them

Explain it simply

Explain it simply

Starting with this lesson, you will build a Task Tracker app step by step over three lessons. Part 1 does not add or delete anything yet. We split the app's skeleton into components and focus only on how data flows from the parent to the child through props.

Picture a notice board in an office. The board itself (TaskTracker) decides which cards are pinned, and each card (TaskItem) simply shows what is written on it. A card has no idea which other cards are on the board. If you get this split right now, adding features in Part 2 and Part 3 becomes far easier.

Problem → Why → Solution

The problem: writing the output by hand instead of the data

A first draft from many React beginners looks like this. Everything lives in one component, three <li> elements are copy-pasted, and the "1 of 3 done" counter is typed by hand. In the browser it looks perfectly correct.

The trouble starts the day you add a fourth task. You must paste another <li>, change the counter to "1 of 4", and move the done class and the badge by hand when a task is finished. Forget one of those places and the screen no longer matches the real data.

App.jsx (first draft)
function App() {
  return (
    <div>
      <h2>My Tasks</h2>
      <p>1 of 3 done</p>
      <ul>
        <li className="task-item done">Learn React basics <span>Done</span></li>
        <li className="task-item">Build Task Tracker project</li>
        <li className="task-item">Add filtering feature</li>
      </ul>
    </div>
  );
}

Why does this draft break so quickly?

This code has no data in it, only the finished result. React's core idea is to write the UI as a function of data. Keep the task data in one place, describe what one task looks like exactly once, let map() produce the rest, and the counter and the list can never disagree.

Core concept: decide who owns the data first

Before writing any JSX, answer two questions: what data does this app have, and which component owns it? For the Task Tracker the data is an array of objects shaped like {id, text, done}. In Part 2 TaskTracker will be the one adding, deleting and toggling tasks, so TaskTracker owns the array. TaskItem only displays one task. We build it in five steps.

1. Fix the data shape

id is a value that identifies a task and never changes, text is what we display, and done is a boolean. These three field names stay exactly the same through Part 2 and Part 3.

2. Keep the list in the parent's state

Write const [tasks] = useState(sampleTasks). We do not take the setter yet; Part 2 adds setTasks. We use state instead of a plain constant because we already know this list is going to change.

3. Pass the child only what it needs

TaskItem needs only text and done. Destructuring them right in the parameter list, function TaskItem({ text, done }), shows what the component accepts on its very first line. Props are read-only for the child; it never changes them.

4. Render with map() and a key

tasks.map() turns each task object into one <TaskItem> element. key={task.id} is for React: between renders, React uses the key to tell which element belongs to which task. The key is not passed to TaskItem as a prop.

5. Derive instead of storing

doneCount is not a second piece of state; it is calculated from tasks with filter on every render. That is why the counter is automatically correct whenever the tasks change.

TaskTracker (parent)TaskItem (child)
HoldsThe tasks array (state)Props (text, done)
JobMap the list, compute the counterShow one task as an <li>
In Part 2Gains add/toggle/delete functionsReceives callback props
Mental model: the board owns, the card shows
  1. Describe the task data once
  2. Parent owns the array in state
  3. map() turns each task into TaskItem
  4. Child reads props, returns an <li>

When the data changes, change only the parent's state. The list, the counter and every badge are produced from that state again.

General pattern

jsx
function Child({ label, active }) {
  return <li className={active ? "item on" : "item"}>{label}</li>;
}

function Parent() {
  const [items] = useState(initialItems);
  const activeCount = items.filter((item) => item.active).length;
  const rows = items.map((item) => (
    <Child key={item.id} label={item.label} active={item.active} />
  ));
  return <section><p>{activeCount} active</p><ul>{rows}</ul></section>;
}

The parent holds the list in state and computes derived values during render. The child shows one item from its destructured props. The key goes on the element returned inside map().

Part 1 code: TaskTracker and TaskItem

In a Vite project, create two files in src/components/, TaskItem.jsx and TaskTracker.jsx, and use TaskTracker from App.jsx. The block below shows the three files separated by comments. The sample data sits outside the component so it is not rebuilt on every render and so Part 2 and Part 3 can reuse it.

src/components (3 files)
// src/components/TaskItem.jsx
function TaskItem({ text, done }) {
  return (
    <li className={done ? "task-item done" : "task-item"}>
      <span className="task-text">{text}</span>
      {done && <span className="badge">Done</span>}
    </li>
  );
}

export default TaskItem;

// src/components/TaskTracker.jsx
import { useState } from "react";
import TaskItem from "./TaskItem";

const sampleTasks = [
  { id: 1, text: "Learn React basics", done: true },
  { id: 2, text: "Build Task Tracker project", done: false },
  { id: 3, text: "Add filtering feature", done: false },
];

function TaskTracker() {
  const [tasks] = useState(sampleTasks);
  const doneCount = tasks.filter((task) => task.done).length;

  return (
    <section className="task-tracker">
      <h2>My Tasks</h2>
      <p>
        {doneCount} of {tasks.length} done
      </p>
      <ul>
        {tasks.map((task) => (
          <TaskItem key={task.id} text={task.text} done={task.done} />
        ))}
      </ul>
    </section>
  );
}

export default TaskTracker;

// src/App.jsx
import TaskTracker from "./components/TaskTracker";

function App() {
  return <TaskTracker />;
}

export default App;

Code breakdown

  1. Props destructured in the signaturefunction TaskItem({ text, done }) {

    React passes props as one object. Destructuring it in the parameter list means the body never has to repeat props.text and props.done.

  2. Conditional badge{done && <span className="badge">Done</span>}

    The badge is rendered only when done is true. When done is false, the expression is false and React renders nothing for it.

  3. State without a setter (yet)const [tasks] = useState(sampleTasks);

    The list is declared as state, but the setter is not taken yet. In Part 2 changing this to const [tasks, setTasks] is all it takes to start adding features.

  4. Derived counterconst doneCount = tasks.filter((task) => task.done).length;

    A plain variable recalculated from tasks on every render. There are no two pieces of state to keep in sync, so the counter and the list can never drift apart.

  5. One TaskItem per task, keyed by id<TaskItem key={task.id} text={task.text} done={task.done} />

    key is for React's list matching, while text and done are the props TaskItem actually receives. TaskItem cannot read key.

You should see
The page shows the heading "My Tasks", the line "1 of 3 done" and three list items. Only "Learn React basics" gets the done class and a Done badge; once you add the CSS from this lesson, its text is shown with a strikethrough.

Why the key must be task.id

Using the index from map((task, index) => ...) as the key shows no error in Part 1, because the list never changes yet. The problem appears in Part 2 when you delete the first task. React pairs the old and new render by key. With index keys, key 0 used to be "Learn React basics" and is now "Build Task Tracker project"; React treats them as the same item and reuses that component, including any state inside it.

The code below is a simplified model of that matching that you can run in Node.

key-matching-model.js
// A simplified model of how React pairs list children by key.
const before = [
  { id: 1, text: "Learn React basics" },
  { id: 2, text: "Build Task Tracker project" },
  { id: 3, text: "Add filtering feature" },
];
const after = before.filter((task) => task.id !== 1); // delete the first task

function matchByKey(label, getKey) {
  const old = new Map(before.map((task, i) => [getKey(task, i), task.text]));
  console.log(label);
  after.forEach((task, i) => {
    const key = getKey(task, i);
    const was = old.get(key);
    const verdict = was === task.text ? "same task, reused" : `was "${was}"`;
    console.log(`  key ${key}: "${task.text}" -> ${verdict}`);
  });
}

matchByKey("index keys:", (task, i) => i);
matchByKey("id keys:", (task) => task.id);

// index keys:
//   key 0: "Build Task Tracker project" -> was "Learn React basics"
//   key 1: "Add filtering feature" -> was "Build Task Tracker project"
// id keys:
//   key 2: "Build Task Tracker project" -> same task, reused
//   key 3: "Add filtering feature" -> same task, reused

key is not a prop

React consumes key itself and does not forward it to the component. If TaskItem ever needs the id, pass it separately as id={task.id}.

Styling the done state

The component only reports the fact "this task is finished" as the done class; CSS decides how that looks. Keeping them apart means a design change touches the stylesheet and never the JSX. Add this to index.css, which main.jsx already imports.

src/index.css
.task-item {
  display: flex;
  gap: 0.5rem;
  align-items: center;
}

.task-item.done .task-text {
  text-decoration: line-through;
  color: #6b7280;
}

.badge {
  font-size: 0.75rem;
  padding: 0 0.4rem;
  border-radius: 999px;
  background: #dcfce7;
}

In real projects

In real projects

Kanban boards, email inboxes, shopping carts and notification panels are all built from this same pair: a container that owns the list and a component that shows one item. Because the item component reads only its props, it can be reused unchanged on a search results page or in a dashboard widget, and it is easy to test: give it a set of props and render it.

In real apps the sample array is replaced by data from an API, and the ids come from the database, so the database id is exactly what you use as the key. Teams usually keep one component per file under src/components/, as this project does, and name each file after its component.

Common mistakes

Common mistakes

Using the array index as the key

key={index} silences the warning, but once items are reordered or deleted React pairs components with the wrong tasks, so state such as a focused checkbox or an edit draft jumps to a different task. Use task.id.

Storing a derived value as state

With const [doneCount, setDoneCount] = useState(1), every change to the tasks also needs a matching setDoneCount call; miss one and the counter is wrong. Anything you can calculate from tasks should be calculated during render.

Repeating props.x instead of destructuring

Writing props.text and props.done everywhere makes the code longer and hides which props the component accepts. Destructuring { text, done } documents the inputs in the signature and makes a misspelled prop name easier to spot.

Mini challenge

Write a priority class helper and a progress label

Each task gets a priority field ("high" or "low"). Write two pure functions: taskClassName(task), which builds the className TaskItem will use, and progressLabel(tasks), which builds the text for the TaskTracker header. You can then call them from the JSX.

  • taskClassName always includes "task-item" and "priority-<priority>", plus "done" when the task is finished
  • A task without a priority is treated as "priority-normal"
  • progressLabel returns "No tasks yet" for an empty list, "All N done!" when everything is finished, and "X of N done" otherwise
  • Neither function changes its input
task-helpers.js
const tasks = [
  // TODO: the three sample tasks, each with a priority ("high" or "low")
];

function taskClassName(task) {
  // TODO: start from "task-item" and "priority-<priority>" (default "normal")
  // TODO: add "done" when task.done is true, then join with spaces
}

function progressLabel(list) {
  // TODO: "No tasks yet" / "All N done!" / "X of N done"
}

// TODO: print taskClassName for every task and progressLabel for a few lists

Expected: One class string per task (the first is "task-item priority-high done"), "task-item priority-normal" for a task with no priority, then the labels "1 of 3 done", "No tasks yet" and "All 3 done!".

Show hint

Push class names into an array and join(" ") them so no stray spaces appear. Handle a missing priority with task.priority ?? "normal". In the component you would write <li className={taskClassName(task)}>.

Show solution
task-helpers.js
const tasks = [
  { id: 1, text: "Learn React basics", done: true, priority: "high" },
  { id: 2, text: "Build Task Tracker project", done: false, priority: "high" },
  { id: 3, text: "Add filtering feature", done: false, priority: "low" },
];

function taskClassName(task) {
  const classes = ["task-item", `priority-${task.priority ?? "normal"}`];
  if (task.done) classes.push("done");
  return classes.join(" ");
}

function progressLabel(list) {
  if (list.length === 0) return "No tasks yet";
  const done = list.filter((task) => task.done).length;
  if (done === list.length) return `All ${list.length} done!`;
  return `${done} of ${list.length} done`;
}

tasks.forEach((task) => console.log(`${task.text}: ${taskClassName(task)}`));
console.log(taskClassName({ id: 4, text: "Old task", done: false }));
console.log(progressLabel(tasks));
console.log(progressLabel([]));
console.log(progressLabel(tasks.map((task) => ({ ...task, done: true }))));

Quick quiz 1 / 3

Given <TaskItem key={task.id} text={task.text} done={task.done} />, what is props.key inside TaskItem?

Quick quiz 2 / 3

With tasks.map((task, index) => <TaskItem key={index} ... />), what can go wrong once Part 2 deletes the first task?

Quick quiz 3 / 3

Where should the "1 of 3 done" text in the header come from?

What to remember

  • Decide the data shape ({id, text, done}) and its owner (TaskTracker) before writing JSX
  • The parent holds the list in state; the child shows one task from its props
  • Inside map(), use the stable task.id as the key, never the index
  • Calculate values such as the counter during render instead of storing them as state

React Documentation — React

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

Project: Task Tracker Setup | Thuta Learning