/

How to Pass a Parameter to Event Handlers in React

How to Pass a Parameter to Event Handlers in React

Learn how to pass a parameter to event handlers in React, specifically for onClick events, without invoking the method on mount.

When working with React functional components, you may need to attach an event handler to the onClick event, or other similar events.

Normally, you would do something like this:

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

But what if you need to pass a parameter? For example, let’s say you have a list of bills and you want to remove one by clicking the β€œX” next to it.

You cannot do this:

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

Because the expression inside onClick will be executed immediately on mount. This would result in deleting all the bills in the list as soon as the app is started.

Instead, you need to use arrow functions like this:

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

Tags: React, event handlers, onClick events, functional components