Build a Todo App with React and LocalStorage
Are you looking to build your first React application and make it interactive? A Todo app is an excellent project for beginners to understand the essential concepts of React, including state management, component lifecycle, and local storage manipulation. In this blog post, we’ll guide you step-by-step on how to create a simple yet functional Todo app, where users can add, delete, and mark tasks as completed, all while utilizing LocalStorage to persist the data. Let’s dive in!
What is React?
React is an open-source JavaScript library developed by Facebook for building user interfaces, especially for single-page applications. Its main goal is to simplify the process of building rich, interactive UIs by breaking them into smaller reusable components. It allows developers to create large web applications that can change data without reloading the page, providing a seamless user experience.
What is LocalStorage?
LocalStorage is part of the Web Storage API that enables web applications to store data in the user’s browser. It allows for the storage of key-value pairs, with no expiration, making it a solid choice for managing application state that needs to persist across browser sessions. In our Todo app, we will use LocalStorage to save the list of tasks so that they remain available even after the page is refreshed.
Setting Up Your React App
To get started, you’ll need a React development environment. If you haven’t already set up one, you can do so with Create React App, a convenient CLI tool.
npx create-react-app my-todo-app
cd my-todo-app
npm start
This will create a new directory called my-todo-app and start a local development server. Open your browser and navigate to http://localhost:3000 to see your newly created React app in action!
Project Structure
Your project should have a simple structure. For our Todo app, we’ll primarily work with src/App.js. You can also create a new file called src/Todo.js to keep the Todo component separate for better organization.
Creating the Todo Component
Let’s create a basic Todo component that allows us to add tasks. In Todo.js, we’re going to define a functional component that includes an input field for adding tasks and a button to submit them.
import React, { useState, useEffect } from 'react';
const Todo = () => {
const [task, setTask] = useState('');
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 handleSubmit = (e) => {
e.preventDefault();
if (!task) return;
setTodos([...todos, { text: task, isCompleted: false }]);
setTask('');
};
const handleDelete = (index) => {
const newTodos = todos.filter((_, i) => i !== index);
setTodos(newTodos);
};
const handleComplete = (index) => {
const newTodos = todos.map((todo, i) =>
i === index ? { ...todo, isCompleted: !todo.isCompleted } : todo
);
setTodos(newTodos);
};
return (
Todo List
setTask(e.target.value)}
placeholder="Enter a new task"
/>
{todos.map((todo, index) => (
-
{todo.text}
))}
);
};
export default Todo;
Integrating Todo Component into App
Now that our Todo component is ready, we need to integrate it into our main application file, App.js. Import the Todo component and include it in the render method.
import React from 'react';
import Todo from './Todo';
function App() {
return (
My Todo App
);
}
export default App;
Handling State with LocalStorage
Our Todo component manages its state using React’s useState and useEffect hooks. When the component mounts for the first time, it reads the Todo list from LocalStorage and sets it into the component state. When the state changes (e.g., adding or deleting a task), we save the new list back to LocalStorage.
Styling Your App
While functionality is important, it’s also essential to have a visually appealing UI. You can apply some basic CSS to style your Todo App. Create a new file called App.css and add the following styles:
body {
font-family: Arial, sans-serif;
background-color: #f4f4f4;
padding: 20px;
}
h1 {
text-align: center;
}
form {
display: flex;
justify-content: center;
margin: 20px 0;
}
input {
padding: 10px;
font-size: 16px;
width: 300px;
}
button {
padding: 10px;
margin-left: 10px;
font-size: 16px;
cursor: pointer;
}
ul {
list-style-type: none;
padding: 0;
}
li {
background: white;
margin: 10px 0;
padding: 15px;
display: flex;
justify-content: space-between;
}
button {
background-color: #007BFF;
color: white;
border: none;
border-radius: 3px;
}
button:hover {
background-color: #0056b3;
}
Don’t forget to import your CSS file in App.js:
import './App.css';
Running Your Todo App
With everything in place, your Todo app should now be functional. Save your changes and navigate to http://localhost:3000. You can now add tasks, mark them as completed, and delete them. Additionally, refreshing the page will not reset your tasks, thanks to LocalStorage.
Conclusion
Congratulations! You have successfully built a Todo app using React and LocalStorage. This project has introduced you to essential concepts in React—component creation, state management, and utilizing the Web Storage API. As you become more comfortable with React, feel free to expand upon this project. Consider adding features like editing tasks, filtering completed tasks, or even user authentication.
We hope you found this guide helpful and that it encourages you to learn more about React and web development!
Further Resources
Happy coding!
