How to pass the event with a parameter to onClick in React
Learn, how to pass the event object with a parameter to the onClick event handler in react.
In a react component, we can pass the parameter to the onClick event handler by using an arrow function which is calling the event handler with parameter.
Example:
function Welcome() {
const checkOut = (name) => {
alert(`Hello ${name}`);
}
return (
<div>
<button onClick={() => checkOut('Gowtham')}>Greet</button> </div>
)
}
export default Welcome;
But, how can we pass both the event
object and parameter?
We can do it like this.
function Welcome() {
const checkOut = (e, name) => {
e.preventDefault();
alert(`Hello ${name}`);
}
return (
<div>
<button onClick={() => checkOut(e,'Gowtham')}>Greet</button> </div>
)
}
export default Welcome;
In the above code, first we passed event
object then parameter
value to the checkOut()
function.