Build a Todo App with React and LocalStorage
Building a Todo application is a common project for developers looking to enhance their skills with React. It’s not just a great way to learn the core principles of React, but also an excellent opportunity to integrate browser storage using LocalStorage. In this tutorial, we’ll walk step-by-step through the process of creating a fully functional Todo app where tasks can be added, completed, and persisted using LocalStorage.
What You Will Learn
- Setting up your React environment
- Creating components for your Todo app
- Managing state with hooks
- Utilizing LocalStorage to persist data
- Styling your application
Prerequisites
Before we dive in, ensure you have:
- Basic knowledge of JavaScript and React
- Node.js and npm installed on your computer
Setting Up Your React Environment
Start by creating a new React application using Create React App. Open your terminal and run the following commands:
npx create-react-app todo-app
After the setup is complete, navigate to the project folder:
cd todo-app
Next, start the development server:
npm start
Your default browser should open with a “Welcome to React” page.
Creating the Todo Application Structure
Now, let’s organize our project by creating two components: TodoList and TodoItem.
Adding Component Files
Inside the src directory, create a subdirectory called components and add two new files: TodoList.js and TodoItem.js.
TodoItem Component
Open TodoItem.js and add the following code:
import React from 'react';
const TodoItem = ({ todo, onComplete, onDelete }) => {
return (
{todo.task}
);
};
export default TodoItem;
TodoList Component
Next, open TodoList.js and implement the TodoList component:
import React from 'react';
import TodoItem from './TodoItem';
const TodoList = ({ todos, onComplete, onDelete }) => {
return (
{todos.map(todo => (
))}
);
};
export default TodoList;
Managing State with Hooks
Now it’s time to manage the state of our Todo app within the main component. Open App.js and set up the state and functionality.
import React, { useState, useEffect } from 'react';
import TodoList from './components/TodoList';
const App = () => {
const [todos, setTodos] = useState([]);
const [task, setTask] = useState('');
useEffect(() => {
const storedTodos = JSON.parse(localStorage.getItem('todos'));
if (storedTodos) {
setTodos(storedTodos);
}
}, []);
useEffect(() => {
localStorage.setItem('todos', JSON.stringify(todos));
}, [todos]);
const addTodo = () => {
if (!task) return;
setTodos([...todos, { id: Date.now(), task, completed: false }]);
setTask('');
};
const completeTodo = (id) => {
setTodos(todos.map(todo => todo.id === id ? { ...todo, completed: true } : todo));
};
const deleteTodo = (id) => {
setTodos(todos.filter(todo => todo.id !== id));
};
return (
Todo App
setTask(e.target.value)}
placeholder="Add a new task"
/>
);
};
export default App;
Understanding LocalStorage
LocalStorage is a simple way to store data in user’s browser to ensure the information persists even when the page is refreshed. In the code above, we achieve this by:
- Using
useEffect
to load existing todos from LocalStorage when the app mounts. - Updating LocalStorage whenever the
todos
state changes.
Styling Your Application
To make our Todo application look attractive, we can add some basic CSS. Create a new file named App.css in the src directory and add the following styles:
.app {
max-width: 400px;
margin: 50px auto;
text-align: center;
}
.todo-list {
margin-top: 20px;
}
.todo-item {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 10px;
}
button {
margin-left: 10px;
}
Don’t forget to import the CSS file into App.js:
import './App.css';
Testing Your Application
Now it’s time to test your implementation. Start the development server again using npm start
and open your browser. You should be able to add, mark, and delete tasks, while ensuring tasks persist even after refreshing the page.
Conclusion
Congratulations! You have successfully built a Todo app using React and LocalStorage. This project not only solidifies your understanding of React concepts, such as components and hooks, but also introduces you to the vital concept of client-side storage.
Feel free to enhance your Todo app further by adding features like editing tasks, setting deadlines, or filtering tasks by completion status. The possibilities are endless!
Additional Resources
By leveraging the skills you’ve gained from this project, you can confidently tackle more complex applications and further advance your development capabilities.