0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

初心者がReactで作るTodoリスト③ トグル機能編

Posted at

トグル機能 - チェック状態の更新

function handleToggleTodo(id) { // todo.idをここで受け取る
    setTodos(previousTodos =>
      previousTodos.map(item =>
        item.id === id ? { ...item, isChecked: !item.isChecked } : item
      ) 
    );
  }

チェックボックスをクリックすると、
そのアイテムのid(todo.id)が引数としてhandleToggleTodoに渡されます。
現在のTodoリスト(previousTodos)をもとにmap()で1つずつループしながらidの一致を見つけます。

  • item.idがクリックされたtodo.idと一致するとき、
    isCheckedの状態を反転(true ↔︎ false)させて、新しいオブジェクトを返します。

  • 一致しないときはそのままitem(オブジェクト)を返します(変更なし)。


こうして更新されたTodoリストがsetTodos()で反映されて画面に表示されます。

2025-05-07 22.18の画像.jpeg

チェック状態に応じて打ち消し線をつける

上記の通りisCheckedは、チェックボックスのON/OFFに応じてtrueかfalseになります。

  • trueのときは打ち消し線のスタイル
    (textDecoration: 'line-through')を適用します。
  • falseのときは通常のスタイルのままです。

各アイテム ⬇︎

<li key={todo.id}>
  <div>
    <input
      type="checkbox"
      onChange={() => onToggleTodo(todo.id)}
      checked={todo.isChecked}
    />
    <span style={todo.isChecked ? { textDecoration: 'line-through' } : {}}>
      {todo.text}
    </span>
  </div>
  <button onClick={() => onDeleteTodo(todo.id)}>削除</button>
</li>

ソースコード(GitHub)

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?