2
2

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リスト② タスク削除機能編

Last updated at Posted at 2025-05-06

タスク削除機能

function handleDeleteTodo(id) {
    setTodos(prevTodos => prevTodos.filter(todo => todo.id !== id));
  }

削除ボタンをクリックしたとき、そのボタンを持つアイテムのidを引数として渡します。
そして現在の配列をもとにfilter()メソッドで、
「todo.id === id」を満たすもの(つまりさっきのidを持つアイテム)を除外して配列を作ります。

この新しく更新された配列をもとに再びレンダリングされるので、画面にはちゃんとアイテムが消えています。

function TodoList({ todos, onDeleteTodo, }) {

  return (
      <ul className="todo-list">
        {todos
          .filter(todo => todo.text.trim())
          .map(todo => {
            return (
              <TodoItem
                key={todo.id}
                todo={todo}
                onDeleteTodo={onDeleteTodo}
              />
            );
          })}
      </ul>
  );
}

// 各アイテム
function TodoItem({ todo, onDeleteTodo}) {
  return (
    <li key={todo.id}>
      <div>
        <span>{todo.text}</span>
      </div>
      <button onClick={() => onDeleteTodo(todo.id)}>削除</button>
    </li>
  );
}
2
2
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
2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?