0% completed
Sometimes, you may want to pass additional arguments to your event handler functions in addition to the default event object (which is automatically passed by React).
Here's the basic syntax of accessing the default event object:
function handleClick(event) { // Access the event properties console.log(event); }
event
object is an argument to the handleClick
function.React allows you to seamlessly integrate custom arguments into your event handlers while still preserving the default event object, offering flexibility in managing both the event data and other parameters.
There are a few scenarios where passing arguments to an event handler might be necessary:
Example 1:
Let's see an example that demonstrates how to create a list of buttons in React, each triggering an event handler that displays a custom alert message when clicked.
import React from 'react'; export default function ButtonList() { const handleClick = (message) => { alert(message); }; return ( <div> <button onClick={() => handleClick('Button 1 clicked')}>Button 1</button> <button onClick={() => handleClick('Button 2 clicked')}>Button 2</button> <button onClick={() => handleClick('Button 3 clicked')}>Button 3</button> </div> ); }
In this example:
handleClick
function accepts a message
argument.handleClick
function using an arrow function within the onClick
event handler.Example 2:
Here’s another example of passing a custom argument to an event handler:
import React, { useState } from 'react'; function App() { const [message, setMessage] = useState(''); const handleClick = (event, customMessage) => { setMessage(customMessage); // Update state with the custom message console.log(event); // Log the event object }; return ( <div> <button onClick={(event) => handleClick(event, 'Hello, React!')}> Click Me </button> <p>{message}</p> </div> ); } export default App;
In this example:
handleClick
function receives two arguments: the default event object and the custom customMessage string.onClick
event handler uses an inline arrow function to call handleClick
with both the event and a custom message ('Hello, React!')......
.....
.....