Events in React
An interface comes alive when it reacts to what the user does. In React,
you listen for events by passing a handler function to props like onClick,
onChange, or onSubmit. These props are written in camelCase and receive a
function, not its result:
function Button() {
function handleClick() {
console.log("You clicked!");
}
return <button onClick={handleClick}>Click</button>;
}
Notice that we pass handleClick (the function), not handleClick(). If
you wrote onClick={handleClick()} the function would run on render,
not on click.
Inline handlers
When the handler is short, it's common to write it as an arrow function inline. This is also useful when you need to pass arguments to it:
<button onClick={() => setCount(count + 1)}>Add</button>
<button onClick={() => greet("Ann")}>Greet Ann</button>
The event object
React passes the handler an event object (by convention we call it e) with
information about what happened and useful methods:
function Link() {
function handle(e) {
e.preventDefault(); // prevents the browser's default behavior
console.log("click intercepted");
}
return <a href="https://example.com" onClick={handle}>Doesn't navigate</a>;
}
e.preventDefault() cancels the browser's default action: a link
navigating, or a form reloading the page when submitted. You'll see it
constantly when working with forms.
There's an event for almost everything:
onClick,onChange,onSubmit,onMouseEnter,onKeyDown... They all receive that event objecte.