DEV Community

Kazutora Hattori
Kazutora Hattori

Posted on

Things to note when passing arguments to React's onClick

Introduction

When creating a filter function in React, I was a little confused by the argument syntax for toggleOptions("optionA")}>, so I've organized it for clarity.

Problem

I originally wrote it like this:

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

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

<button onClick={toggle}>A</button>
Enter fullscreen mode Exit fullscreen mode

The reason it doesn't work when clicked is because the key isn't passed.

Solution

Write it so that "A" is passed when clicked.

<button onClick={() => toggle("A")}>A</button>
<button onClick={() => toggle("B")}>B</button>
Enter fullscreen mode Exit fullscreen mode

This passes "A" and "B", which toggle between true and false, respectively.

Summary
I'd like to summarize the basics once again.

Top comments (0)