Borislav Hadzhiev
Mon May 02 2022·1 min read
Photo by SGC
To pass an event and parameter onClick in React:
onClick
prop of the element.event
object and call handleClick
.handleClick
.const App = () => { const handleClick = (event, param) => { console.log(event); console.log(param); }; return ( <div> <button onClick={event => handleClick(event, 'hello world')}> Click </button> </div> ); }; export default App;
We set the onClick
prop on the button element to an inline arrow function.
The arrow function takes the event
object and calls the handleClick
function
passing it the event and a parameter.
Notice that we are passing a function to the onClick
prop and not the result
of calling one.
<button onClick={event => handleClick(event, 'hello world')}> Click </button>
If you invoke the function when passing it to the onClick
prop, e.g.
onClick={handleClick()}
, it would get immediately called when the component
mounts.
When a function is passed to the onClick
prop, it will only get invoked when
the event is triggered an it will always get called with the event
object.