React Beginner 5: Building Your First Todo App

In this tutorial, you will combine components, props, state, and events to build a simple but functional Todo app in React.

Introduction

Now that you know how to create components, use props, manage state, and handle events, it’s time to build a small app. The Todo app is a classic beginner project that lets you create, display, and delete tasks.

1. Project Setup

Use the React project you created in Beginner 2 (Vite or Create React App). Ensure it’s running with:

npm run dev

2. Create Todo Component

Create a new file Todo.jsx in src:

function Todo({ task, onDelete }) {
  return (
    <div>
      <span>{task}</span>
      <button onClick={onDelete}>Delete</button>
    </div>
  );
}

export default Todo;

This component receives a task and a delete function from its parent.

3. Update App Component

Edit App.jsx to manage the task list:

import { useState } from 'react';
import Todo from './Todo.jsx';

function App() {
  const [tasks, setTasks] = useState([]);
  const [input, setInput] = useState('');

  const addTask = () => {
    if(input) {
      setTasks([...tasks, input]);
      setInput('');
    }
  };

  const deleteTask = (index) => {
    const newTasks = tasks.filter((_, i) => i !== index);
    setTasks(newTasks);
  };

  return (
    <div>
      <h1>Todo App</h1>
      <input 
        type="text" 
        value={input} 
        onChange={e => setInput(e.target.value)} 
        placeholder="Add a task" 
      />
      <button onClick={addTask}>Add</button>
      <div>
        {tasks.map((task, index) => (
          <Todo key={index} task={task} onDelete={() => deleteTask(index)} />
        ))}
      </div>
    </div>
  );
}

export default App;

4. Test Your App

Run your app in the browser. You should be able to:

  • Type a task in the input field
  • Click “Add” to add the task to the list
  • Click “Delete” to remove a task

5. Summary

In this tutorial, you learned how to:

  • Use state to manage a list of tasks
  • Pass props to child components
  • Handle events like adding and deleting tasks
  • Render lists of components dynamically

This small app combines everything from the previous tutorials and gives you a real, interactive React project.

Next, in React Beginner 6, we will fetch data from an API, including how to connect to a Spring Boot backend.

Previous Article

React Beginner 4: Props, State & Events

Next Article

React Beginner 6: Fetching Data from an API

Write a Comment

Leave a Comment

Your email address will not be published. Required fields are marked *

Subscribe to our Newsletter

Subscribe to our email newsletter to get the latest posts delivered right to your email.
Pure inspiration, zero spam ✨