Building a simple to-do list app with React

Building a Simple To-Do List App with React

Creating a to-do list app is a classic project for developers, especially those wanting to learn and improve their skills in React. This hands-on guide will walk you through the steps of building a simple, yet functional, to-do list application using React. By the end of this article, you'll have a solid understanding of React components, state management, and how to structure a basic app.

Why Build a To-Do List App?

A to-do list app is a great starting point for several reasons:

  • Fundamental Concepts: It helps you grasp foundational concepts of React, including components, props, and state management.
  • User Interaction: You’ll learn how to handle user inputs and events, a crucial aspect of any interactive application.
  • Real-World Application: Task management is a universal need, making this app useful in everyday life.

Getting Started

Before we dive into code, ensure you have a development environment set up with Node.js and npm. If you haven’t already, you can create a new React app using Create React App, a tool that sets up everything you need to start a React project.

Step 1: Create a New React App

Open your terminal and run the following command:

npx create-react-app todo-list
cd todo-list

This command creates a new directory called todo-list with all the necessary files.

Step 2: Clean Up the Default Template

Open your project in a code editor (like VSCode) and remove unnecessary files to simplify your setup. You can delete everything in the src folder except for App.js and index.js. Your src folder should now look like this:

src
├── App.js
└── index.js

Step 3: Set Up the Basic Structure

Let's start coding our To-Do List app. First, we need to create some basic components. Open App.js and replace its contents with the following code:

import React, { useState } from 'react';
import './App.css';

function App() {
    const [tasks, setTasks] = useState([]);
    const [taskInput, setTaskInput] = useState('');

    const handleInputChange = (e) => {
        setTaskInput(e.target.value);
    };

    const addTask = () => {
        if (taskInput.trim() !== '') {
            setTasks([...tasks, taskInput]);
            setTaskInput('');
        }
    };

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

    return (
        <div className="App">
            <h1>To-Do List</h1>
            <input
                type="text"
                value={taskInput}
                onChange={handleInputChange}
                placeholder="Add a new task"
            />
            <button onClick={addTask}>Add Task</button>
            <ul>
                {tasks.map((task, index) => (
                    <li key={index}>
                        {task} <button onClick={() => removeTask(index)}>Remove</button>
                    </li>
                ))}
            </ul>
        </div>
    );
}

export default App;

Code Breakdown

State Management

  • useState: We utilize React's useState hook to manage our tasks and input values.
  • tasks: An array that holds our current tasks.
  • taskInput: A string that stores the value of the input field.

Event Handlers

  • handleInputChange: Updates taskInput whenever the user types in the input field.
  • addTask: Adds the current task to the tasks array and resets the input field if the task is not empty.
  • removeTask: Removes a task from the list based on its index.

Step 4: Styling the App

To make your app visually appealing, you can add some basic CSS. Create a new file called App.css in the src folder and add the following styles:

.App {
    text-align: center;
    margin: 20px;
}

input {
    padding: 10px;
    width: 300px;
    margin-right: 10px;
}

button {
    padding: 10px;
}

ul {
    list-style-type: none;
    padding: 0;
}

li {
    display: flex;
    justify-content: space-between;
    margin: 10px 0;
}

Step 5: Running Your App

Now that you've built your to-do list app, it's time to see it in action. In your terminal, run:

npm start

This command will start the development server and open your app in the browser. You should now see your to-do list app where you can add and remove tasks.

Troubleshooting Common Issues

  1. Input Not Updating: Ensure that your onChange event is correctly bound to the input field.
  2. Tasks Not Adding: Check if you’re correctly updating the tasks state with setTasks([...tasks, taskInput]).
  3. Removing Tasks: Make sure you pass the correct index to the removeTask function.

Conclusion

Congratulations! You've built a simple yet functional to-do list app using React. This project not only enhances your coding skills but also provides a practical tool for task management.

Next Steps

  • Enhancements: Consider adding features like editing tasks, marking them as complete, or persisting them in local storage.
  • Explore State Management Libraries: As your app grows, you may want to explore libraries like Redux for more complex state management.

Building a to-do list app is just the beginning. Use this foundational knowledge to explore more complex projects and continue your journey in web development!

SR
Syed
Rizwan

About the Author

Syed Rizwan is a Machine Learning Engineer with 5 years of experience in AI, IoT, and Industrial Automation.