How to pass a parameter to an event handler or callback ?
In React, to pass a parameter to an event handler or callback simply means to execute that function or code when the event is triggered. It links the events to the respective functions.
Prerequisites:
Approach
We will define a function to create a window alert and link it to the click event using an event handler. When the event triggers the corresponding function will be executed creating an alert on the browser screen.
Steps to create React Project
Step 1: Use this command in the terminal to initialize a react project.
npx create-react-app project_name
Step 2: After creating your react project move into the folder to perform different operations.
cd project_name
Project Structure: 
Example 1:This example uses an event handler that sends a Welcome message i.e. Alert whenever you click the button.
Javascript
// Filename - App.js import React from "react" ; class App extends React.Component { call() { alert( "Welcome to Geeks for Geeeks!" ); } render() { return ( <div> <h3>React Example for event handlers</h3> <button onClick={ this .call}> Click the button! </button> </div> ); } } export default App; |
Step to run the application: Open the terminal and type the following command.
npm start
Output: This output will be visible on http://localhost:3000/ on browser window.
Example 2: This example uses arrow funciton to execute the alert as the event handler and show message
Javascript
// Filename - App.js import React from "react" ; class App extends React.Component { call(message, event) { alert(message); } render() { return ( <div> <h3>React Example for event handler</h3> { //Creating a arrow function } <button onClick={(event) => this .call( "Your message" , event) } > Click the button! </button> </div> ); } } export default App; |
Step to run the application: Open the terminal and type the following command.
npm start
Output: This output will be visible on http://localhost:3000/ on browser window.
Example 3: In this example, we will use Bind Method that is also used to pass the parameters in functions of class-based components.
Javascript
// Filename - App.js import React from "react" ; class App extends React.Component { call(message) { alert(message); } render() { return ( <div> <h3>React Example for event handlers</h3> <button onClick={ this .call.bind( this , "Your message" )} > Click the button! </button> </div> ); } } export default App; |
Step to run the application: Open the terminal and type the following command.
npm start
Output: This output will be visible on http://localhost:3000/ on browser window.