Passing Arguments to Event Handlers in ReactJS
There are two ways in which you can pass arguments to Even Handlers in ReactJS.
- Arrow Function –
<button onClick={(e)=>this.handleClick(id,e)}> Click Me </button>
- Bind Method –
<button onClick={(this.handleClick.bind(this,id)}> Click Me </button>
Note:
- In both cases, the ‘e’ argument representing the React event will be passed as a second argument after the ID.
- With an arrow function, you need to pass it explicitly, but with bind method any further arguments are automatically forwared.
Let us understand by example-
import React, { Component } from "react"; class Tutorial extends Component{ state = {id:1}; handleClick = (pid) => { console.log(pid+ " Button Clicked."); } handleClickArgs = () => { this.handleClick(this.state.id); } render(){ return( <div> <h1>Passing Arguments to Event Handlers in ReactJS</h1> <button onClick={this.handleClickArgs}>Delete</button> </div> ); } } export default Tutorial;
The above code can be achieved by using anonymous function.
import React, { Component } from "react"; class Tutorial extends Component{ state = {id:1}; handleClick = (pid) => { console.log(pid+ " Button Clicked."); } render(){ return( <div> <h1>Passing Arguments to Event Handlers in ReactJS</h1> <button onClick = { e => { this.handleClick(this.state.id) } }>Delete</button> </div> ); } } export default Tutorial;
Passing arguments in Event Handler using Bind method
import React, { Component } from "react"; class Tutorial extends Component{ state = {id:1}; handleClick = (pid) => { console.log(pid+ " Button Clicked."); } render(){ return( <div> <h1>Passing Arguments to Event Handlers in ReactJS</h1> <button onClick = { this.handleClick.bind(this, this.state.id) }>Delete</button> </div> ); } } export default Tutorial;