Syw.Frontend

✅ React 기초 강좌

5단계. 간단한 프로젝트 실습

5-2. 완료 체크 기능 및 스타일 적용

🎯 학습 목표

  • 각 항목마다 isDone 상태를 추가해 완료 여부를 구분한다.
  • 체크박스를 토글하면 완료 상태를 업데이트한다.
  • 완료된 항목은 취소선 + 연한 회색으로 표시해 구분한다.

📄 예제 코드: App.jsx

import { useState } from 'react';

function App() {
  const [todos, setTodos] = useState([]);
  const [text, setText] = useState('');

  const handleAdd = () => {
    const trimmed = text.trim();
    if (trimmed === '') return;

    const newTodo = {
      id: Date.now(),
      content: trimmed,
      isDone: false,
    };
    setTodos([newTodo, ...todos]);
    setText('');
  };

  const handleDelete = (id) => {
    setTodos(todos.filter((todo) => todo.id !== id));
  };

  const handleToggle = (id) => {
    setTodos(
      todos.map((todo) =>
        todo.id === id ? { ...todo, isDone: !todo.isDone } : todo
      )
    );
  };

  const handleKeyDown = (e) => {
    if (e.key === 'Enter') handleAdd();
  };

  return (
    <div style={{ padding: '30px' }}>
      <h1>✅ Todo 리스트</h1>

      <div style={{ marginBottom: '20px' }}>
        <input type="text"
          value={text}
          onChange={(e) => setText(e.target.value)}
          onKeyDown={handleKeyDown}
          placeholder="할 일을 입력하세요"
        />
        <button onClick={handleAdd}>추가</button>
      </div>

      <ul style={{ listStyle: 'none', padding: 0 }}>
        {todos.map((todo) => (
          <li key={todo.id} style={{ marginBottom: '10px' }}>
            <input type="checkbox"
              checked={todo.isDone}
              onChange={() => handleToggle(todo.id)}
            />
            <span style={{
                marginLeft: '10px',
                textDecoration: todo.isDone ? 'line-through' : 'none',
                color: todo.isDone ? '#999' : '#000',
              }}
            >
              {todo.content}
            </span>
            <button onClick={() => handleDelete(todo.id)}
              style={{ marginLeft: '10px' }}
            >
              삭제
            </button>
          </li>
        ))}
      </ul>

      <p>총 {todos.length}개의 할 일이 있습니다.</p>
    </div>
  );
}

export default App;

✅ 추가된 기능

기능 설명
✅ 체크박스 항목 완료 상태 토글 가능
취소선 완료된 항목은 취소선과 회색 텍스트
✔️ 상태 유지 isDone 속성으로 상태 관리

📌 연습 정리

  • useState 상태에 isDone 속성 추가
  • .map() 안에서 항목 업데이트 (불변성 유지!)
  • textDecoration, color로 스타일 조건부 처리

GitHub - heroyooi/react-app at ch5_2

💬 댓글

    ※ 로그인 후 댓글을 작성할 수 있습니다.