Learn how to build a Todo App using React, a popular JavaScript library for building user interfaces. This tutorial will guide you through the process step by step.

Prerequisites

  • Basic knowledge of JavaScript
  • Familiarity with React
  • Node.js and npm installed

Step 1: Setting Up the Project

To start, create a new directory for your project and navigate into it:

mkdir todo-app-react
cd todo-app-react

Initialize a new React project using Create React App:

npx create-react-app .

Change into the project directory:

cd todo-app-react

Step 2: Creating the Todo List Component

Create a new file called TodoList.js in the src directory:

touch src/TodoList.js

Open TodoList.js and add the following code:

import React from 'react';

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

export default TodoList;

Step 3: Adding State to the App

In App.js, import the TodoList component and add state to manage the list of todos:

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

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

  return (
    <div>
      <h1>Todo App</h1>
      <TodoList todos={todos} />
    </div>
  );
};

export default App;

Step 4: Adding a Form to Add Todos

Create a new file called TodoForm.js in the src directory:

touch src/TodoForm.js

Open TodoForm.js and add the following code:

import React, { useState } from 'react';

const TodoForm = ({ addTodo }) => {
  const [input, setInput] = useState('');

  const handleSubmit = (e) => {
    e.preventDefault();
    addTodo(input);
    setInput('');
  };

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

export default TodoForm;

Step 5: Integrating the Form with the App

In App.js, import the TodoForm component and add a function to handle adding todos:

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

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

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

  return (
    <div>
      <h1>Todo App</h1>
      <TodoForm addTodo={addTodo} />
      <TodoList todos={todos} />
    </div>
  );
};

export default App;

Step 6: Running the App

To run the app, use the following command:

npm start

Your Todo App should now be running on http://localhost:3000.

Todo App

For more information on React and building web applications, check out our React tutorials.