How to Build a Simple To-Do App with React
A to-do app is a great beginner-friendly project to learn React. In this guide, we’ll build a simple to-do application where users can add, mark, and delete tasks.
1. Setting Up the React Project
First, create a new React app using Create React App:
npx create-react-app todo-app
cd todo-app
npm start
2. Creating the To-Do Component
Inside the src
folder, create a new file TodoApp.js
and define the basic structure of our app:
import React, { useState } from "react";
import "./TodoApp.css";
function TodoApp() {
const [tasks, setTasks] = useState([]);
const [task, setTask] = useState("");
const addTask = () => {
if (task.trim()) {
setTasks([...tasks, { text: task, completed: false }]);
setTask("");
}
};
const toggleTask = (index) => {
const newTasks = tasks.map((t, i) =>
i === index ? { ...t, completed: !t.completed } : t
);
setTasks(newTasks);
};
const deleteTask = (index) => {
setTasks(tasks.filter((_, i) => i !== index));
};
return (
<div className="todo-container">
<h1>To-Do App</h1>
<div className="input-section">
<input
type="text"
value={task}
onChange={(e) => setTask(e.target.value)}
placeholder="Enter a task"
/>
<button onClick={addTask}>Add</button>
</div>
<ul>
{tasks.map((t, index) => (
<li key={index} className={t.completed ? "completed" : ""}>
<span onClick={() => toggleTask(index)}>{t.text}</span>
<button onClick={() => deleteTask(index)}>X</button>
</li>
))}
</ul>
</div>
);
}
export default TodoApp;
3. Styling the To-Do App
Create a TodoApp.css
file inside src
and add the following styles:
.todo-container {
max-width: 400px;
margin: auto;
text-align: center;
background: #f9f9f9;
padding: 20px;
border-radius: 10px;
}
.input-section {
display: flex;
justify-content: space-between;
}
input {
width: 70%;
padding: 8px;
}
button {
padding: 8px 12px;
background-color: #41AEA9;
color: white;
border: none;
cursor: pointer;
}
ul {
list-style: none;
padding: 0;
}
li {
display: flex;
justify-content: space-between;
padding: 8px;
background: white;
margin: 5px 0;
border-radius: 5px;
cursor: pointer;
}
.completed {
text-decoration: line-through;
color: gray;
}
4. Rendering the Component
Now, open src/App.js
and replace its content with:
import React from "react";
import TodoApp from "./TodoApp";
function App() {
return (
<div>
<TodoApp />
</div>
);
}
export default App;
5. Running the To-Do App
Save all the files and start the development server:
npm start
Your to-do app is now functional! Users can add tasks, mark them as completed, and delete them.
Conclusion
This simple React to-do app introduces you to key concepts like state management and event handling. You can expand this by adding features like local storage, categories, or a due date for tasks.
Post Comment