Building a Simple To-Do List App with React 🚀

Abdul Haseeb - Jul 13 - - Dev Community

Introduction:
In this tutorial, we'll walk through the process of building a simple to-do list app using React. This project will help you understand the basics of React components, state management, and event handling. By the end of this tutorial, you'll have a functional to-do list app that you can further enhance with additional features.

Prerequisites:

  • Basic knowledge of JavaScript and HTML.
  • Node.js installed on your machine.
  • A code editor like VS Code.

Step 1: Setting Up the Project
First, let's set up our React project using Create React App. Open your terminal and run the following commands:

npx create-react-app todo-app
cd todo-app
npm start
Enter fullscreen mode Exit fullscreen mode

This will create a new React project and start the development server. Open your browser and navigate to http://localhost:3000 to see the default React app.

Step 2: Creating the To-Do List Component
Next, we'll create a new component for our to-do list. Create a new file called TodoList.js in the src directory and add the following code:

import React, { useState } from 'react';

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

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

  return (
    <div>
      <h1>To-Do List</h1>
      <input
        type="text"
        value={input}
        onChange={(e) => setInput(e.target.value)}
        placeholder="Enter a new task"
      />
      <button onClick={addTask}>Add Task</button>
      <ul>
        {tasks.map((task, index) => (
          <li key={index}>{task}</li>
        ))}
      </ul>
    </div>
  );
}

export default TodoList;
Enter fullscreen mode Exit fullscreen mode

Step 3: Using the To-Do List Component in App.js
Now, let's use our TodoList component in the main App.js file. Open src/App.js and update it as follows:

import React from 'react';
import TodoList from './TodoList';
import './App.css';

function App() {
  return (
    <div className="App">
      <TodoList />
    </div>
  );
}

export default App;
Enter fullscreen mode Exit fullscreen mode

Step 4: Adding Some Styling
To make our app look better, let's add some basic styling. Open src/App.css and add the following styles:

.App {
  text-align: center;
}

input {
  margin-right: 10px;
}

button {
  margin-left: 10px;
}

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

li {
  background: #f4f4f4;
  margin: 5px 0;
  padding: 10px;
  border-radius: 4px;
}
Enter fullscreen mode Exit fullscreen mode

Conclusion:
That's it! You've built a simple to-do list app with React. You can now add, display, and clear tasks. Feel free to extend this app by adding features like task deletion, task editing, or even persisting tasks in local storage.

Further Reading:

. . . . . . . . . . . . . . . . . . .