How to pass event and parameter onClick in React
To pass event and parameter onClick in React, declare an event handler function and then pass it to the onClick prop of the element inside an inline arrow function.
Using React onClick event handler you 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 should be written as onClick
in a React app, and, React event handlers should be inside curly braces like onClick={clickHandler}
.
Pass the event and parameters
You 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. You can pass many parameters to the clickHandler
function as per our needs.
Pass parameters without event object
You can pass parameters without an 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;
Why the warning: Invalid event handler property `onclick`. Did you mean `onClick`
The warning: “Invalid event handler property `onclick`. Did you mean `onClick`” occurs when you give event handler property in lowercase letters. To solve the issue give the event handler property onClick in camelCase letters.
For example, onclick={clickHandler}
will cause an error. It should be in camelCase letters like onClick={clickHandler}
.
On datainfinities.com, Read articles all around JavaScript, React, Node.js, PHP, Laravel, and Shopify.
Related Blogs
Programmatically update query params in React Router
Build password strength checker in React
How to use Profiler API in React to measure render performance
Each child in a list should have a unique "key" prop
Warning: The tag is unrecognized in this browser
Get the current route using React Router
The style prop expects a mapping from style properties to values, not a string
Get the Mouse Position (coordinates) in React
Explore All Blogs