Skip to content

How to pass a parameter to event handlers in React

New Course Coming Soon:

Get Really Good at Git

Find out how to pass a parameter to onClick events for example, without invoking the method on mount

When you work on a React function component you might have the need to attach an event to onClick (or other events).

You usually do:

<button onClick={addBill}>Add</button>

But what if you have to pass a parameter? Say you have a list of bills, and you want to remove one by clicking the “X” next to it.

You can’t do:

<button onClick={removeBill(index)}>𝗫</button>

because the expression inside onClick is going to be executed on mount. This is going to delete all the bills in the list, as soon as the app is started.

Instead, this is what you need to do, using arrow functions:

<button onClick={() => removeBill(index)}>𝗫</button>
Are you intimidated by Git? Can’t figure out merge vs rebase? Are you afraid of screwing up something any time you have to do something in Git? Do you rely on ChatGPT or random people’s answer on StackOverflow to fix your problems? Your coworkers are tired of explaining Git to you all the time? Git is something we all need to use, but few of us really master it. I created this course to improve your Git (and GitHub) knowledge at a radical level. A course that helps you feel less frustrated with Git. Launching Summer 2024. Join the waiting list!
→ Get my React Beginner's Handbook
→ Read my full React Tutorial on The Valley of Code

Here is how can I help you: