Site icon Learn Web Development & Programming, Artificial Intelligence, WordPress, Shopify Articles

Passing Arguments to Event Handlers

Passing Arguments to Event Handlers

If you are working on a React function component, you may need to add an event to Click (or other events). Before start this article i will suggest you to read Event Handling in React Element.

You usually do:

But what if you’re going to have to pass a parameter? Say you have a list of ids, and you want to remove one by clicking on the “Delete” next to it.

You can’t do:

Because the expression inside onClick will be performed on the button. This will delete all the ids in the list as soon as the app starts. This is what you need to do:

Using Arrow Function:

Using Bind Method:

Note:-

Let’s start with an example to learn in detail :

Step-1: First we will write a simple event handling code

In the above example, i created an Employee class component. Here you can see, i also define state without constructor, because i am not passing any props with component. handleClick is an event handler with arrow function which is calling from onClick button. Right now we are not passing any argument using event handler.

Step-2: Now we will pass an argument but under the Event Handler using another function or method

In the above example, we are passing id as argument under handleClickArg Event Handler. handleClick is an another function with is calling under Event Handler with argument.

Step-3: Now, I will pass the second argument “e” (react event object) in the above example

In the above example, I am passing the react event object (e) as the second argument which is used to perform various events. When you will run above code then you will get the event objects in the console.

Step-4: Now, we will pass both arguments to event handler Using Arrow Function

From the above code, we will change

to (e)=>{ this.handleClick(this.state.id,e); } as anonymous arrow function and it will trigger from onClick event.

In the above example code, (e)=>{ this.handleClick(this.state.id,e); } is an anonymous arrow function which is calling from onClick as event handler.

Passing arguments to event handler Using Bind Function or Method

In the above code, I only need to replace 

With the below code:

You don’t need to pass “e” (React Event Object) as an argument. With the bind method React Event Object automatically calls under event handler.

Handling Events – React

State in React Component

Props in ReactJS

What is JSX in React?

Exit mobile version