React를 사용하여 테마 토글이 포함된 Todo 앱 구축

WBOY
풀어 주다: 2024-09-10 22:33:11
원래의
820명이 탐색했습니다.

Building a Todo App with Theme Toggle Using React

소개

이 튜토리얼에서는 React를 사용하여 Todo List 웹 애플리케이션을 구축해 보겠습니다. 이 프로젝트는 상태 관리, 이벤트 처리 및 React의 목록 작업을 이해하는 데 도움이 됩니다. React 개발 기술을 강화하려는 초보자에게 적합합니다.

프로젝트 개요

Todo List 애플리케이션을 사용하면 사용자는 작업을 추가하고 완료로 표시하고 제거할 수 있습니다. 일상적인 작업을 관리하기 위한 깔끔한 인터페이스를 제공합니다. 이 프로젝트는 단순하면서도 동적인 애플리케이션의 상태를 관리하기 위해 React를 사용하는 방법을 보여줍니다.

특징

  • 새 작업 추가: 사용자가 목록에 작업을 추가할 수 있습니다.
  • 완료로 표시: 사용자가 작업을 완료로 표시할 수 있습니다.
  • 작업 삭제: 사용자가 목록에서 작업을 삭제할 수 있습니다.
  • 로컬 스토리지: localStorage를 사용하여 페이지를 다시 로드해도 작업을 유지합니다.

사용된 기술

  • React: 사용자 인터페이스를 구축하고 구성 요소 상태를 관리합니다.
  • CSS: 애플리케이션 스타일을 지정합니다.
  • JavaScript: 핵심 논리 및 기능에 대한

프로젝트 구조

프로젝트 구조는 일반적인 React 프로젝트 레이아웃을 따릅니다.

├── public
├── src
│   ├── components
│   │   ├── TodoList.jsx
│   │   ├── TodoItem.jsx
│   ├── App.jsx
│   ├── App.css
│   ├── index.js
│   └── index.css
├── package.json
└── README.md
로그인 후 복사

주요 구성 요소

  • TodoList.jsx: 할일 목록 표시 및 관리를 담당합니다.
  • TodoItem.jsx: 개별 할 일 항목을 완료로 표시하거나 삭제하는 등 관리합니다.

코드 설명

TodoList 구성 요소

이 구성요소는 새 작업 추가 및 목록 렌더링을 포함하여 전체 할일 목록의 상태를 처리합니다.

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>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;
로그인 후 복사

TodoItem 구성 요소

TodoItem 구성 요소는 완료로 표시하거나 삭제하는 옵션과 함께 각 작업의 표시를 관리합니다.

const TodoItem = ({ task, index, toggleCompletion, deleteTask }) => {
  return (
    
로그인 후 복사
  • toggleCompletion(index)}>{task.text}
  • ); }; export default TodoItem;

    이 구성요소에서는 상위 TodoList로부터 prop을 수신하고 작업 완료 전환 또는 작업 삭제와 같은 작업을 처리합니다.

    앱 구성요소

    App.jsx는 애플리케이션의 루트 역할을 하며 TodoList 구성 요소를 렌더링합니다.

    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>TODO</h1>
              </div>
              <div classname="mode" onclick="{toggleTheme}">
                <img src="%7BisLightTheme" moon : sun alt="React를 사용하여 테마 토글이 포함된 Todo 앱 구축">
              </div>
            </div>
            <todo></todo>
            <div classname="footer">
            <p>Made with ❤️ by Abhishek Gurjar</p>
          </div>
          </div>
    
        </div>
      );
    };
    
    export default App;
    
    
    로그인 후 복사

    CSS 스타일링

    CSS는 Todo List 애플리케이션이 사용자 친화적이고 반응성이 뛰어나도록 보장합니다.

    * {
      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;
    }
    
    로그인 후 복사

    스타일은 작업 관리를 허용하면서 Todo 목록을 간단하고 깔끔하게 만듭니다.

    설치 및 사용법

    시작하려면 저장소를 복제하고 종속성을 설치하세요.

    git clone https://github.com/abhishekgurjar-in/todo_list.git
    cd todo-list
    npm install
    npm start
    
    로그인 후 복사

    애플리케이션은 http://localhost:3000에서 실행되기 시작합니다.

    라이브 데모

    여기에서 Todo List의 라이브 데모를 확인하세요.

    결론

    Todo List 프로젝트는 React에서 상태, 목록, 이벤트 처리 작업을 연습할 수 있는 좋은 방법입니다. localStorage를 사용하여 세션 전반에 걸쳐 데이터를 유지할 수 있는 유용한 애플리케이션을 구축하는 방법을 보여줍니다.

    크레딧

    • 영감: 간단하고 효과적인 작업 관리 도구에 대한 필요성에서 영감을 얻었습니다.

    작가

    Abhishek Gurjar는 열정적인 웹 개발자입니다. GitHub에서 더 많은 프로젝트를 확인하실 수 있습니다.

    위 내용은 React를 사용하여 테마 토글이 포함된 Todo 앱 구축의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

    원천:dev.to
    본 웹사이트의 성명
    본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
    인기 튜토리얼
    더>
    최신 다운로드
    더>
    웹 효과
    웹사이트 소스 코드
    웹사이트 자료
    프론트엔드 템플릿
    회사 소개 부인 성명 Sitemap
    PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!