DEV Community

Cover image for Creating a To-Do App with React and Saving Data to Local Storage
kiraaziz
kiraaziz

Posted on

Creating a To-Do App with React and Saving Data to Local Storage

This tutorial will guide you through the process of creating a simple To-Do app using React. We will also implement the functionality to save the To-Do items to the browser's local storage. This tutorial assumes you have a basic understanding of HTML, CSS, and JavaScript.

Prerequisites

Before we begin, make sure you have the following software installed on your machine:

  • Node.js (v12 or higher)
  • npm (Node Package Manager)

Step 1: Setup

First, let's set up the basic project structure:

  1. Create a new project directory and navigate into it.
  2. Open a terminal or command prompt and run the following command to initialize a new React project:
npx create-react-app todo-app
Enter fullscreen mode Exit fullscreen mode
  1. Once the project is created, navigate into the project directory:
cd todo-app
Enter fullscreen mode Exit fullscreen mode
  1. Start the development server by running the following command:
npm start
Enter fullscreen mode Exit fullscreen mode

You should see the default React app running in your browser at http://localhost:3000. Now we're ready to start building our To-Do app!

Step 2: Create the To-Do Component

In this step, we'll create the main component for our To-Do app.

  1. Open the src directory in your project.
  2. Delete all the existing files in the src directory except index.js and App.js.
  3. Create a new file called Todo.js inside the src directory.
  4. Open Todo.js and add the following code:
import React, { useState } from 'react';

const Todo = () => {
  const [todos, setTodos] = useState([]);
  const [inputValue, setInputValue] = useState('');

  const handleInputChange = (e) => {
    setInputValue(e.target.value);
  };

  const handleSubmit = (e) => {
    e.preventDefault();
    if (inputValue.trim() !== '') {
      setTodos([...todos, inputValue]);
      setInputValue('');
    }
  };

  return (
    <div>
      <h1>Todo App</h1>
      <form onSubmit={handleSubmit}>
        <input
          type="text"
          value={inputValue}
          onChange={handleInputChange}
          placeholder="Enter a new task"
        />
        <button type="submit">Add Task</button>
      </form>
      <ul>
        {todos.map((todo, index) => (
          <li key={index}>{todo}</li>
        ))}
      </ul>
    </div>
  );
};

export default Todo;
Enter fullscreen mode Exit fullscreen mode

Step 3: Update the App Component

Next, let's update the App component to render our Todo component.

  1. Open src/App.js.
  2. Replace the existing code with the following:
import React from 'react';
import Todo from './Todo';

const App = () => {
  return (
    <div className="App">
      <Todo />
    </div>
  );
};

export default App;
Enter fullscreen mode Exit fullscreen mode

Step 4: Styling the App

Let's add some basic styling to our To-Do app using CSS.

  1. Open the src directory.
  2. Create a new file called App.css.
  3. Open App.css and add the following styles:
.App {
  text-align: center;
  padding: 20px;
}

form {
  margin-bottom: 20px;
}

input[type='text'] {
  padding: 5px;
  width: 200px;
  margin-right: 10px

;
}

button {
  padding: 5px 10px;
}
Enter fullscreen mode Exit fullscreen mode
  1. Open App.js.
  2. Add the following import statement at the top of the file:
import './App.css';
Enter fullscreen mode Exit fullscreen mode

Step 5: Implement Local Storage

Now let's implement the functionality to save the To-Do items to the browser's local storage.

  1. Open src/Todo.js.
  2. Add the following code inside the handleSubmit function, after setInputValue(''):
localStorage.setItem('todos', JSON.stringify([...todos, inputValue]));
Enter fullscreen mode Exit fullscreen mode
  1. Add the following code inside the Todo component, before the return statement:
React.useEffect(() => {
  const storedTodos = localStorage.getItem('todos');
  if (storedTodos) {
    setTodos(JSON.parse(storedTodos));
  }
}, []);
Enter fullscreen mode Exit fullscreen mode
  1. Save the file.

Step 6: Finalize and Test

Congratulations! You have successfully created a To-Do app with React and implemented local storage.

  1. Go to your browser and open the To-Do app at http://localhost:3000.
  2. Enter a task in the input field and click "Add Task." The task should be added to the list below.
  3. Refresh the page. The added task should still be visible.

Conclusion

In this tutorial, you learned how to create a simple To-Do app using React and save the To-Do items to the browser's local storage. You can further enhance this app by adding features like deleting tasks, marking tasks as completed, or using a more advanced state management solution like Redux.

Feel free to experiment and modify the code to suit your needs. Happy coding!

Top comments (0)