DEV Community

Cover image for Resolving React Hook Error and Building a Simple Todo List Page
Bhavik Mistry
Bhavik Mistry

Posted on

Resolving React Hook Error and Building a Simple Todo List Page

Hello fellow programmers! I invite you to read this blog post as I share the details of my recent experience making contributions to the open-source "-React-Learning-Project." My effort was centered around fixing a React Hook error. I'll walk you through the steps I took to fix the problem while sharing my experience, and I'll explain how creating a simple Todo List page was a crucial part of the solution.

Background

The issue (#12) reported a React Hook error, indicating the misuse of a React Hook without importing it from the 'react' library. To address this issue, I created a new file, TodoList.js, under the src/components directory. The goal was not only to fix the error but also to enhance the project by adding a functional Todo List feature.

Fixing the React Hook Error

The error was related to using React Hooks without proper import statements. I addressed this by importing the useState hook from the 'react' library at the beginning of the TodoList.js file. This ensured that React Hooks were correctly utilized within the component.

import React, { useState } from "react";
Enter fullscreen mode Exit fullscreen mode

Implementing the Todo List
I proceeded to build a simple Todo List page using React. Here are the key components of the implementation:

  • State Management: I utilized the useState hook to manage the state of the todo items and the input for adding new todos.

  • Adding Todos: Implemented the handleAddTodo function to add a new todo to the list when the "Add" button is clicked.

  • Deleting Todos: Created the handleDeleteTodo function to remove a todo when the "Delete" button is clicked.

  • Toggling Todo Status: Implemented the handleToggleTodo function to toggle the completion status of a todo when the checkbox is clicked.

  const [todos, setTodos] = useState([]);
  const [newTodo, setNewTodo] = useState("");

  const handleAddTodo = () => {
    if (newTodo.trim() !== "") {
      setTodos([...todos, { text: newTodo.trim(), checked: false }]);
      setNewTodo("");
    }
  };

  const handleDeleteTodo = (index) => {
    const newTodos = [...todos];
    newTodos.splice(index, 1);
    setTodos(newTodos);
  };

  const handleToggleTodo = (index) => {
    const newTodos = [...todos];
    newTodos[index].checked = !newTodos[index].checked;
    setTodos(newTodos);
  };

Enter fullscreen mode Exit fullscreen mode

This is the complete src/components/TodoList.js file.

Testing and Measuring Progress

During the development process, I thoroughly tested the Todo List functionality to ensure that it worked as expected. I measured my progress by checking off the tasks mentioned in the issue and verifying that the React Hook error was resolved.

This is my Pull Request #14

Top comments (0)