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?

More than 3 years have passed since last update.

【React】チェックボックスのチェックが付かない現象の解決

Last updated at Posted at 2021-07-14

本記事では、チェックが付かない問題を解決するためある記述をしますが、その記述をすることでなぜ「チェックが付かない問題」が解決されるのかわかっていません。(わかったら追記していきます)。

チェックが付かないコード

まずはチェックが付かなかったコードを以下に記載します。

  //チェックボックスの処理
  const switchCheckBox = (e) => {
    e.preventDefault();
    const todoId = todo.id;
    const newTodos = todos.map((todo) => {
      if (todo.id === todoId) {
        return {
          id: todo.id,
          title: todo.title,
          checkFlug: !todo.checkFlug,
        };
      }
      return todo;
    });
    setTodo(newTodos);
  };

処理の解説

onClickでswitchCheckBoxが呼ばれることでチェックが付きます。 

switchCheckBox関数 

todosというtodoを持つ配列をmap関数で回しています。その際、一致したidのチェックボックスのみがtrueになった配列をnewTodosとして新たに生成しています。それをsetTodo(useState)に引数として渡すことで再レンダリングが起きるので、チェックボックスが更新されるはずなのですが更新されませんでした。
todoがもつcheckFlugが更新されていないのかとDeveloperToolで確認したのですが、しっかりと更新されていてわけワカメでした。

解決

e.preventDefaultが必要なかったみたいです。
以下で解決でした。

  //チェックボックスの処理
  const switchCheckBox = () => {
    const todoId = todo.id;
    const newTodos = todos.map((todo) => {
      if (todo.id === todoId) {
        return {
          id: todo.id,
          title: todo.title,
          checkFlug: !todo.checkFlug,
        };
      }
      return todo;
    });
    setTodo(newTodos);
  };

原因

e.preventDefault();についての理解ができていなかった。勉強します。

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?