How to pass event and parameter onClick in React
Using React onClick event handler we can call a function and trigger an action when a user clicks an element(eg button).
The event names should be written in camelCase, so the onclick
event is written as onClick
in a React app, and, React event handlers should be inside curly braces.
Pass the event and parameters
We can pass the event and parameters onClick in React as given below example.
function App() {
const clickHandler = (event, message) => {
alert(message);
}
return (
<div>
<button onClick={(event) => clickHandler(event, "Hello World!")}>Say Hello</button>
</div>
);
}
export default App;
Here we set the inline arrow function (event) => clickHandler(event, "Hello World!")
as props to the onClick event handler in the button.
The arrow function takes the event as an argument and calls clickHandler
function. We can pass many parameters to the clickHandler
function as per our needs.
Pass parameters without event object
We can pass parameters without event object as given below.
function App() {
const clickHandler = (message) => {
alert(message);
}
return (
<div>
<button onClick={() => clickHandler("Hello World!")}>Say Hello</button>
</div>
);
}
export default App;