How to create a simple to-do app with React

How to Create a Simple To-Do App with React

Creating a to-do app is a classic exercise for developers looking to sharpen their skills, especially in React. Not only is it an excellent way to understand the core concepts of React, but it also provides a practical tool that you can use in your daily life. In this article, we’ll walk you through how to build a simple to-do app using React, covering everything from setup to deployment.

What is React?

React is a popular JavaScript library for building user interfaces, particularly for single-page applications. It allows developers to create large web applications that can change data, without reloading the page. Key features include:

  • Component-Based Architecture: Break down your UI into reusable components.
  • Virtual DOM: Efficiently update and render components.
  • Unidirectional Data Flow: Data flows in one direction, making it easier to understand how data changes affect the UI.

Use Cases for a To-Do App

A to-do app can be used in various contexts, including:

  • Personal Productivity: Keep track of daily tasks.
  • Project Management: Manage tasks within a team.
  • Learning Tool: A practical example to learn programming concepts and frameworks.

Prerequisites

Before we dive into the code, ensure you have:

  • Node.js and npm installed on your machine.
  • Basic knowledge of JavaScript and React.

Step-by-Step Guide to Building a To-Do App

Step 1: Setting Up Your Development Environment

  1. Create a New React App: Use the create-react-app command to set up your project quickly.

bash npx create-react-app todo-app cd todo-app

  1. Start the Development Server: Run the following command to start your app.

bash npm start

Step 2: Structuring Your App

In your src folder, create the following components:

  • TodoApp.js: The main component.
  • TodoList.js: Displays the list of tasks.
  • TodoItem.js: Represents each individual task.
  • TodoForm.js: A form for adding new tasks.

Step 3: Building the Main Component

Open TodoApp.js and set up the main structure of your app.

import React, { useState } from 'react';
import TodoList from './TodoList';
import TodoForm from './TodoForm';

const TodoApp = () => {
  const [todos, setTodos] = useState([]);

  const addTodo = (todo) => {
    setTodos([...todos, todo]);
  };

  const removeTodo = (index) => {
    const newTodos = todos.filter((_, i) => i !== index);
    setTodos(newTodos);
  };

  return (
    <div>
      <h1>To-Do App</h1>
      <TodoForm addTodo={addTodo} />
      <TodoList todos={todos} removeTodo={removeTodo} />
    </div>
  );
};

export default TodoApp;

Step 4: Creating the TodoForm Component

Next, let’s create the TodoForm.js file for adding new tasks.

import React, { useState } from 'react';

const TodoForm = ({ addTodo }) => {
  const [inputValue, setInputValue] = useState('');

  const handleSubmit = (e) => {
    e.preventDefault();
    if (!inputValue) return;
    addTodo({ text: inputValue, completed: false });
    setInputValue('');
  };

  return (
    <form onSubmit={handleSubmit}>
      <input 
        type="text" 
        value={inputValue} 
        onChange={(e) => setInputValue(e.target.value)} 
        placeholder="Add a new task" 
      />
      <button type="submit">Add</button>
    </form>
  );
};

export default TodoForm;

Step 5: Building the TodoList and TodoItem Components

Now, let’s create the TodoList.js and TodoItem.js files.

TodoList.js:

import React from 'react';
import TodoItem from './TodoItem';

const TodoList = ({ todos, removeTodo }) => {
  return (
    <ul>
      {todos.map((todo, index) => (
        <TodoItem key={index} todo={todo} index={index} removeTodo={removeTodo} />
      ))}
    </ul>
  );
};

export default TodoList;

TodoItem.js:

import React from 'react';

const TodoItem = ({ todo, index, removeTodo }) => {
  return (
    <li>
      <span>{todo.text}</span>
      <button onClick={() => removeTodo(index)}>Remove</button>
    </li>
  );
};

export default TodoItem;

Step 6: Adding Basic Styling

To make your app visually appealing, add some CSS in App.css.

body {
  font-family: Arial, sans-serif;
  background-color: #f4f4f4;
}

h1 {
  text-align: center;
}

form {
  display: flex;
  justify-content: center;
  margin-bottom: 20px;
}

input {
  padding: 10px;
  border: 1px solid #ccc;
  border-radius: 4px;
}

button {
  padding: 10px 15px;
  margin-left: 10px;
  background-color: #5cb85c;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

Step 7: Testing Your App

Run your application and test the functionality. You should be able to add and remove tasks seamlessly.

Troubleshooting Common Issues

  • Tasks Not Adding: Ensure that the addTodo function is called correctly and that the form submission is handled properly.
  • Tasks Not Removing: Verify that the removeTodo function is correctly modifying the state.

Conclusion

Congratulations! You've just built a simple to-do app using React. This project not only enhances your understanding of React components, state management, and event handling but also serves as a foundation for more complex applications.

Feel free to expand this app by adding features like editing tasks, marking them as complete, or even integrating local storage for persistence. The possibilities are endless! Happy coding!

SR
Syed
Rizwan

About the Author

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