Table of Contents
Todo List
TODO
Home Web Front-end CSS Tutorial Building a Todo App with Theme Toggle Using React

Building a Todo App with Theme Toggle Using React

Sep 10, 2024 pm 10:33 PM

Building a Todo App with Theme Toggle Using React

Introduction

In this tutorial, we'll build a Todo List Web Application using React. This project helps in understanding state management, event handling, and working with lists in React. It’s perfect for beginners looking to strengthen their skills in React development.

Project Overview

The Todo List application allows users to add, mark as completed, and remove tasks. It offers a clean interface for managing daily tasks. This project showcases how React can be used to manage the state of a simple yet dynamic application.

Features

  • Add New Task: Users can add tasks to the list.
  • Mark as Completed: Users can mark tasks as done.
  • Delete Task: Users can delete tasks from the list.
  • Local Storage: Persists tasks across page reloads using localStorage.

Technologies Used

  • React: For building the user interface and managing component state.
  • CSS: For styling the application.
  • JavaScript: For the core logic and functionality.

Project Structure

The project structure follows a typical React project layout:

├── public
├── src
│   ├── components
│   │   ├── TodoList.jsx
│   │   ├── TodoItem.jsx
│   ├── App.jsx
│   ├── App.css
│   ├── index.js
│   └── index.css
├── package.json
└── README.md
Copy after login

Key Components

  • TodoList.jsx: Handles the display and management of the todo list.
  • TodoItem.jsx: Manages individual todo items, including marking them as completed or deleting them.

Code Explanation

TodoList Component

This component handles the state of the entire todo list, including adding new tasks and rendering the list.

import { useState, useEffect } from "react";
import TodoItem from "./TodoItem";

const TodoList = () => {
  const [task, setTask] = useState("");
  const [tasks, setTasks] = useState([]);

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

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

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

  const toggleCompletion = (index) => {
    const newTasks = tasks.map((t, i) =>
      i === index ? { ...t, completed: !t.completed } : t
    );
    setTasks(newTasks);
  };

  const deleteTask = (index) => {
    const newTasks = tasks.filter((_, i) => i !== index);
    setTasks(newTasks);
  };

  return (
    <div classname="todo-list">
      <h1 id="Todo-List">Todo List</h1>
      <input type="text" value="{task}" onchange="{(e)"> setTask(e.target.value)}
        placeholder="Add a new task"
      />
      <button onclick="{addTask}">Add Task</button>
      <ul>
        {tasks.map((t, index) => (
          <todoitem key="{index}" task="{t}" index="{index}" togglecompletion="{toggleCompletion}" deletetask="{deleteTask}"></todoitem>
        ))}
      </ul>
    </div>
  );
};

export default TodoList;
Copy after login

TodoItem Component

The TodoItem component manages the display of each task, along with options to mark it as completed or delete it.

const TodoItem = ({ task, index, toggleCompletion, deleteTask }) => {
  return (
    
Copy after login
  • toggleCompletion(index)}>{task.text}
  • ); }; export default TodoItem;

    In this component, we receive props from the parent TodoList and handle actions like toggling task completion or deleting the task.

    App Component

    The App.jsx serves as the root of the application, rendering the TodoList component.

    import  { useState } from "react";
    import "./App.css";
    import TodoList from './components/TodoList';
    import sun from "./assets/images/icon-sun.svg";
    import moon from "./assets/images/icon-moon.svg";
    
    const App = () => {
      const [isLightTheme, setIsLightTheme] = useState(false);
    
      const toggleTheme = () => {
        setIsLightTheme(!isLightTheme);
      };
    
      return (
        <div classname="{isLightTheme" :>
          <div classname="app">
            <div classname="header">
              <div classname="title">
                <h1 id="TODO">TODO</h1>
              </div>
              <div classname="mode" onclick="{toggleTheme}">
                <img src="%7BisLightTheme" moon : sun alt="Building a Todo App with Theme Toggle Using React">
              </div>
            </div>
            <todo></todo>
            <div classname="footer">
            <p>Made with ❤️ by Abhishek Gurjar</p>
          </div>
          </div>
    
        </div>
      );
    };
    
    export default App;
    
    
    Copy after login

    CSS Styling

    The CSS ensures the Todo List application is user-friendly and responsive.

    * {
      box-sizing: border-box;
    }
    body {
      margin: 0;
      padding: 0;
      font-family: Josefin Sans, sans-serif;
    }
    
    .app {
      width: 100%;
      height: 100vh;
      background-color: #161722;
      color: white;
      background-image: url(./assets//images/bg-desktop-dark.jpg);
      background-repeat: no-repeat;
      background-size: contain;
      background-position-x: center;
      background-position-y: top;
      display: flex;
      align-items: center;
      justify-content: flex-start;
      flex-direction: column;
    }
    .header {
      width: 350px;
      margin-top: 20px;
      display: flex;
      align-items: center;
      justify-content: space-between;
    }
    .title h1 {
      font-size: 30px;
      letter-spacing: 7px;
    }
    .mode {
      display: flex;
      align-items: center;
      justify-content: center;
    }
    .mode img {
      width: 22px;
    }
    
    .todo {
      width: 350px;
      flex-direction: column;
      display: flex;
      align-items: center;
      justify-content: flex-start;
    }
    .input-box {
      border-bottom: 1px solid white;
      display: flex;
      align-items: center;
      justify-content: center;
      background-color: #25273c;
      width: 100%;
      gap: 10px;
      padding: 8px;
      border-radius: 10px;
    }
    .check-circle {
      width: 12px;
      height: 12px;
      border-radius: 50%;
      border: 1px solid white;
      display: flex;
      align-items: center;
      justify-content: center;
      background-image: linear-gradient(to right,hsl(230, 50%, 20%) , hsl(280, 46%, 28%));
    }
    
    .input-task {
      width: 90%;
      border: none;
      color: white;
      background-color: #25273c;
    }
    .input-task:focus {
      outline: none;
    }
    .todo-list {
    
      margin-top: 20px;
      width: 350px;
      background-color: #25273c;
    }
    .todo-box {
    
      margin-inline: 15px;
      margin-block: 10px;
      width: 100%;
      display: flex;
      align-items: center;
      justify-content: flex-start;
      gap: 15px;
    }
    .todo-box .cross{
    width: 14px;
    }
    .details {
      margin-bottom: 40px;
    border-bottom: 1px solid white;
      width: 350px;
      display: flex;
      align-items: center;
      justify-content: space-evenly;
      background-color: #25273c;
      font-size: 12px;
      padding: 12px;
      border-bottom-right-radius: 7px;
      border-bottom-left-radius: 7px;
    }
    
    .details .clickBtn{
      cursor: pointer;
    
    }
    .details .clickBtn:hover{
    color: #3074fd;
    
    }
    
    
    /* //light Theme  */
    
    
    .light-theme .app {
      background-color: #fff;
      color: #000;
      background-image: url(./assets//images/bg-desktop-light.jpg);
    }
    
    .light-theme .header {
    color: white;
    }
    
    .light-theme .input-box{
      background-color: white;
      color: black;
      border-bottom: 1px solid black;
    }
    .light-theme input{
      background-color: white;
      color: black;
    }
    .light-theme .check-circle{
      border:1px solid black;
    
    }
    .light-theme  .todo-list{
      background-color: white;
      color: black;
    }
    .light-theme .details{
      border-bottom: 1px solid black;
      background-color: white;
      color: black;
    }
    
    .footer{
     margin: 40px;
    }
    
    Copy after login

    The styles ensure the Todo List is simple and clean while allowing for task management.

    Installation and Usage

    To get started, clone the repository and install the dependencies:

    git clone https://github.com/abhishekgurjar-in/todo_list.git
    cd todo-list
    npm install
    npm start
    
    Copy after login

    The application will start running at http://localhost:3000.

    Live Demo

    Check out the live demo of the Todo List here.

    Conclusion

    The Todo List project is a great way to practice working with state, lists, and event handling in React. It demonstrates how to build a useful application that can persist data across sessions using localStorage.

    Credits

    • Inspiration: Inspired by the need for a simple and effective task management tool.

    Author

    Abhishek Gurjar is a passionate web developer. You can check out more of his projects on GitHub.

    The above is the detailed content of Building a Todo App with Theme Toggle Using React. For more information, please follow other related articles on the PHP Chinese website!

    Statement of this Website
    The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

    Hot AI Tools

    Undresser.AI Undress

    Undresser.AI Undress

    AI-powered app for creating realistic nude photos

    AI Clothes Remover

    AI Clothes Remover

    Online AI tool for removing clothes from photos.

    Undress AI Tool

    Undress AI Tool

    Undress images for free

    Clothoff.io

    Clothoff.io

    AI clothes remover

    AI Hentai Generator

    AI Hentai Generator

    Generate AI Hentai for free.

    Hot Article

    R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
    2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
    Repo: How To Revive Teammates
    4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
    Hello Kitty Island Adventure: How To Get Giant Seeds
    4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

    Hot Tools

    Notepad++7.3.1

    Notepad++7.3.1

    Easy-to-use and free code editor

    SublimeText3 Chinese version

    SublimeText3 Chinese version

    Chinese version, very easy to use

    Zend Studio 13.0.1

    Zend Studio 13.0.1

    Powerful PHP integrated development environment

    Dreamweaver CS6

    Dreamweaver CS6

    Visual web development tools

    SublimeText3 Mac version

    SublimeText3 Mac version

    God-level code editing software (SublimeText3)

    Demystifying Screen Readers: Accessible Forms & Best Practices Demystifying Screen Readers: Accessible Forms & Best Practices Mar 08, 2025 am 09:45 AM

    This is the 3rd post in a small series we did on form accessibility. If you missed the second post, check out "Managing User Focus with :focus-visible". In

    Create a JavaScript Contact Form With the Smart Forms Framework Create a JavaScript Contact Form With the Smart Forms Framework Mar 07, 2025 am 11:33 AM

    This tutorial demonstrates creating professional-looking JavaScript forms using the Smart Forms framework (note: no longer available). While the framework itself is unavailable, the principles and techniques remain relevant for other form builders.

    Adding Box Shadows to WordPress Blocks and Elements Adding Box Shadows to WordPress Blocks and Elements Mar 09, 2025 pm 12:53 PM

    The CSS box-shadow and outline properties gained theme.json support in WordPress 6.1. Let&#039;s look at a few examples of how it works in real themes, and what options we have to apply these styles to WordPress blocks and elements.

    Create an Inline Text Editor With the contentEditable Attribute Create an Inline Text Editor With the contentEditable Attribute Mar 02, 2025 am 09:03 AM

    Building an inline text editor isn't trivial. The process starts by making the target element editable, handling potential SyntaxError exceptions along the way. Creating Your Editor To build this editor, you'll need to dynamically modify the content

    Making Your First Custom Svelte Transition Making Your First Custom Svelte Transition Mar 15, 2025 am 11:08 AM

    The Svelte transition API provides a way to animate components when they enter or leave the document, including custom Svelte transitions.

    Working With GraphQL Caching Working With GraphQL Caching Mar 19, 2025 am 09:36 AM

    If you’ve recently started working with GraphQL, or reviewed its pros and cons, you’ve no doubt heard things like “GraphQL doesn’t support caching” or

    Comparing the 5 Best PHP Form Builders (And 3 Free Scripts) Comparing the 5 Best PHP Form Builders (And 3 Free Scripts) Mar 04, 2025 am 10:22 AM

    This article explores the top PHP form builder scripts available on Envato Market, comparing their features, flexibility, and design. Before diving into specific options, let's understand what a PHP form builder is and why you'd use one. A PHP form

    File Upload With Multer in Node.js and Express File Upload With Multer in Node.js and Express Mar 02, 2025 am 09:15 AM

    This tutorial guides you through building a file upload system using Node.js, Express, and Multer. We'll cover single and multiple file uploads, and even demonstrate storing images in a MongoDB database for later retrieval. First, set up your projec

    See all articles