Skip to content

How to pass a parameter to event handlers in React

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>

→ Get my React Beginner's Handbook

I wrote 21 books to help you become a better developer:

  • HTML Handbook
  • Next.js Pages Router Handbook
  • Alpine.js Handbook
  • HTMX Handbook
  • TypeScript Handbook
  • React Handbook
  • SQL Handbook
  • Git Cheat Sheet
  • Laravel Handbook
  • Express Handbook
  • Swift Handbook
  • Go Handbook
  • PHP Handbook
  • Python Handbook
  • Linux Commands Handbook
  • C Handbook
  • JavaScript Handbook
  • Svelte Handbook
  • CSS Handbook
  • Node.js Handbook
  • Vue Handbook
...download them all now!

Related posts that talk about react: