Build a Todo App with React and LocalStorage: A Step-by-Step Guide
To-do lists are a fundamental part of keeping track of tasks, projects, and schedules. They’re simple yet effective tools for personal productivity. Building a Todo app provides a perfect opportunity to work with React, a powerful JavaScript library for building user interfaces, and to get acquainted with local storage for data persistence. In this guide, we will walk through creating a Todo app from scratch using React and LocalStorage.
Why Use React for Your Todo App?
React provides a component-based architecture that promotes the reuse of code and makes maintenance easier. Its virtual DOM enhances performance, especially in applications where updates are frequent, such as when managing a list of tasks.
Setting Up Your Development Environment
Before diving into code, ensure you have the necessary tools:
- Node.js: Download and install from nodejs.org.
- Code Editor: Use any code editor of your choice. Visual Studio Code is highly recommended.
Now, let’s create our React application.
Creating a New React App
To set up a new React app, run the following command in your terminal:
npx create-react-app todo-app
Once the setup is complete, navigate into the app directory:
cd todo-app
Installing Required Libraries
For this tutorial, we won’t be using any additional libraries; React comes packed with features sufficient for our Todo app. However, if you want to manage state more efficiently in larger applications, consider installing libraries like Redux.
Structures of the App
We will divide our app into a few simple components:
- App: The main component that will hold our state.
- TodoList: This component will render the list of to-do items.
- TodoItem: Each individual item in our to-do list.
- AddTodo: A component that allows users to add new tasks.
Setting Up Our Main App Component
Open src/App.js and start with the following code:
import React, { useState, useEffect } from 'react';
import TodoList from './TodoList';
import AddTodo from './AddTodo';
function App() {
const [todos, setTodos] = useState([]);
useEffect(() => {
const storedTodos = JSON.parse(localStorage.getItem('todos'));
if (storedTodos) {
setTodos(storedTodos);
}
}, []);
useEffect(() => {
localStorage.setItem('todos', JSON.stringify(todos));
}, [todos]);
const addTodo = (todo) => {
setTodos([...todos, todo]);
};
const removeTodo = (todoToRemove) => {
setTodos(todos.filter(todo => todo !== todoToRemove));
};
return (
Todo App
);
}
export default App;
Here’s a brief breakdown of what’s happening:
- We initialize the
todosstate as an empty array usinguseState. - In the first
useEffect, we retrieve any saved tasks fromlocalStoragewhen the component mounts. - In the second
useEffect, we save the current state of todos tolocalStoragewhenever it changes. - We define the
addTodoandremoveTodofunctions to manage the to-do items.
Creating the Add Todo Component
Next, let’s create the AddTodo component. Create a new file in src called AddTodo.js and add the following code:
import React, { useState } from 'react';
function AddTodo({ addTodo }) {
const [todo, setTodo] = useState('');
const handleAddTodo = (event) => {
event.preventDefault();
if (!todo) return;
addTodo(todo);
setTodo('');
};
return (
setTodo(e.target.value)}
placeholder="Add a new task..."
/>
);
}
export default AddTodo;
Creating the Todo List Component
Now, let’s create the TodoList component that renders each Todo item. Create a new file in src named TodoList.js:
import React from 'react';
import TodoItem from './TodoItem';
function TodoList({ todos, removeTodo }) {
return (
{todos.map((todo, index) => (
))}
);
}
export default TodoList;
Creating the Todo Item Component
Next, let’s implement the TodoItem component in the TodoItem.js file:
import React from 'react';
function TodoItem({ todo, removeTodo }) {
return (
{todo}
);
}
export default TodoItem;
Styling the Application
Given the basic structure of our Todo app, let’s add some simple styling. Create a CSS file called App.css in the src directory:
body {
font-family: Arial, sans-serif;
background-color: #f7f7f7;
}
h1 {
text-align: center;
}
form {
display: flex;
justify-content: center;
margin: 20px 0;
}
input[type="text"] {
padding: 10px;
border: 1px solid #ccc;
border-radius: 5px;
width: 300px;
}
button {
padding: 10px;
margin-left: 10px;
background-color: #28a745;
color: white;
border: none;
border-radius: 5px;
cursor: pointer;
}
button:hover {
background-color: #218838;
}
ul {
list-style-type: none;
padding: 0;
}
li {
display: flex;
justify-content: space-between;
padding: 10px;
margin: 5px;
background-color: white;
border-radius: 5px;
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}
Don’t forget to import this CSS file in your main App.js file:
import './App.css';
Running Your Application
Now that everything is set up, it’s time to see your Todo app in action. Run the following command in your terminal:
npm start
This will start your React application, and you should be able to see it in your browser at http://localhost:3000.
Enhancements and Next Steps
Your basic Todo app is up and running! Here are some enhancements you can consider:
- Editing Todos: Implement functionality to edit existing todos.
- Task Completion: Add a feature to mark tasks as complete.
- Filter Todos: Allow users to filter tasks by completed or pending.
- Styling Improvements: Use CSS frameworks like Bootstrap or Tailwind CSS for improved aesthetics.
Conclusion
Building a Todo app with React and LocalStorage is a fantastic way to enhance your web development skills. You have learned how to handle state, manage component communication, and utilize local storage for data persistence. Continue building upon this base and exploring the rich ecosystem of React to create even more powerful applications!
Happy coding!
