The JSX Syntax lesson already flagged the two headline differences from HTML: event names are camelCase, and take a real function instead of a string.
function Button() {
function handleClick() {
alert('Button clicked!');
}
return <button onClick={handleClick}>Click me</button>;
}Pass the function, don't call it
onClick={handleClick()} — with parentheses — calls the function immediately during render, not when clicked, and passes whatever it returns (usually undefined) as the handler instead. Pass the function itself: onClick={handleClick}.
For a handler that needs an argument, an inline arrow function is the standard way to pass one along without calling the handler immediately:
function FruitList({ fruits, onSelect }) {
return (
<ul>
{fruits.map((fruit) => (
<li key={fruit} onClick={() => onSelect(fruit)}>
{fruit}
</li>
))}
</ul>
);
}React passes a synthetic event to every handler — a cross-browser wrapper around the native browser event, with the same familiar properties and methods you already know from the JavaScript Events lesson:
function Form() {
function handleSubmit(e) {
e.preventDefault(); // same method, same purpose, as plain JS
console.log('Submitted');
}
return <form onSubmit={handleSubmit}><button type="submit">Send</button></form>;
}| Prop | Fires when |
|---|---|
| onClick | An element is clicked |
| onChange | An input's value changes |
| onSubmit | A form is submitted |
| onMouseEnter / onMouseLeave | The pointer enters or leaves an element |
| onKeyDown | A key is pressed |
The Forms in React lesson right after this one puts onChange and onSubmit to real use.