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 found that I still didn't fully understand how to write the arguments for toggleOptions("optionA")}>, so I've re-organized it.

Problem

I originally wrote it like this:

<button onClick={toggleOptions("optionA")}>Option A</button>
Enter fullscreen mode Exit fullscreen mode

This resulted in the function being executed automatically before the click.

Cause

toggleOptions("optionA") executes a function, so it runs when React renders.

Solution

If you want it to run when clicked, you need to pass a function.

<button onClick={() => toggleOptions("optionA")}>Option A</button>
Enter fullscreen mode Exit fullscreen mode

() => means "Call this function when clicked."

Summary
I would like to summarize the basics once again.

Top comments (0)