Pass a function as a camelCase prop on the element, like onClick={handleClick}. React calls it with an event object when the event fires, such as a click or a key press.
function Button() {
const handleClick = (event) => {
event.preventDefault();
console.log('Button clicked!');
console.log('Event type:', event.type);
};
return (
<button onClick={handleClick}>
Click me
</button>
);
}
Pass the function itself, not a call. onClick={handleClick()} would run the handler during rendering instead of on click.
The event object is a SyntheticEvent, React's wrapper around the native browser event. It behaves the same across browsers and has the usual methods and properties, such as preventDefault() and type.
This answer doesn't lend itself to a diagram - it reads best . No credits were charged.
Why there's no diagram: “”
The interactive diagram is below the answer - jump to diagram ↓ · Below it, the related concept . Jump to it ↓
The diagram below the answer is the concept . Jump to it ↓