Delete Elements and Auto-Update Tasks in React: Add a Clear All Button to Your To-Do App

React Project - Build a Complete Todo App from Scratch with Advanced Features

In this guide, we will build a fully functional Todo App using React, covering state management, event handling, and advanced features like filtering and local storage.

Key Features

- Add, edit, and delete tasks.
- Mark tasks as completed.
- Filter tasks (All, Completed, Pending).
- Store tasks in local storage for persistence.
- Display a real-time digital clock showing the current date and time.
- Clear all tasks with a single button.

Installation and Setup

    
// Create a new React project
npx create-react-app todo-app
cd todo-app
npm start
    
  

Todo App Component with Digital Clock & Clear All Button

    
import React, { useState, useEffect } from "react";

function TodoApp() {
  const [tasks, setTasks] = useState([]);
  const [newTask, setNewTask] = useState("");
  const [currentTime, setCurrentTime] = useState(new Date());

  useEffect(() => {
    const storedTasks = JSON.parse(localStorage.getItem("tasks")) || [];
    setTasks(storedTasks);
  }, []);

  useEffect(() => {
    localStorage.setItem("tasks", JSON.stringify(tasks));
  }, [tasks]);

  useEffect(() => {
    const timer = setInterval(() => {
      setCurrentTime(new Date());
    }, 1000);
    return () => clearInterval(timer);
  }, []);

  const addTask = () => {
    if (newTask.trim() === "") return;
    setTasks([...tasks, { text: newTask, completed: false }]);
    setNewTask("");
  };

  const toggleTask = (index) => {
    const updatedTasks = tasks.map((task, i) =>
      i === index ? { ...task, completed: !task.completed } : task
    );
    setTasks(updatedTasks);
  };

  const clearTasks = () => {
    setTasks([]);
    localStorage.removeItem("tasks");
  };

  return (
    

Todo List

Current Time: {currentTime.toLocaleTimeString()}

setNewTask(e.target.value)} className="border p-2 w-full mb-2" />
    {tasks.map((task, index) => (
  • toggleTask(index)} className={`p-2 border rounded-md cursor-pointer ${task.completed ? 'line-through text-gray-500' : ''}`} > {task.text}
  • ))}
); } export default TodoApp;

Challenge: Add More Features

- Implement a task editing feature.
- Add categories or priorities to tasks.
- Improve UI with animations and better styling.