Things to note when passing arguments to React’s onClick



This content originally appeared on DEV Community and was authored by Kazutora Hattori

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>

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>

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

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


This content originally appeared on DEV Community and was authored by Kazutora Hattori