1
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のonClickに引数を渡すときの注意点

Posted at

はじめに

Reactでフィルター機能を作っているとき、
toggleOptions("optionA")}> の
「引数の書き方」で少し混乱したので、分かりやすく整理してまとめました。

問題

最初はこう書いていました

const [options, setOptions] = useState({ A: false, B: false });

const toggle = (key) => {
  setOptions(prev => ({ ...prev, [key]: !prev[key] }));
};

<button onClick={toggle}>A</button> 

クリックしても動かない原因は、key が渡されていないからです。

解決策

クリックされたときに "A" を渡すように書きます

<button onClick={() => toggle("A")}>A</button>
<button onClick={() => toggle("B")}>B</button>

これで "A" や "B" が渡り、それぞれ true / false が切り替わります。

まとめ

基本をアウトプットしながらもう一度整理していきたいと思います。

1
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
1
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?