React ยท Chapter 7 of 42
Handling Events
React lets you respond to user interactions like clicks, typing, and form submissions using event handlers. React events are named using camelCase, like `onClick` and `onChange`.
Event handlers in React receive a synthetic event object that wraps the native browser event for cross-browser consistency.
Attaching handlers
Pass a function reference (not a call) to event props: `<button onClick={handleClick}>`. Avoid calling the function immediately.
Passing arguments
To pass arguments to a handler, wrap the call in an arrow function: `onClick={() => handleClick(id)}`.
Example 1 (jsx)
function Button() {
function handleClick() {
console.log("Button clicked!");
}
return <button onClick={handleClick}>Click me</button>;
}Output
Button clicked!Clicking the button logs a message to the console.
Key points
- React events use camelCase names like onClick, onChange.
- Pass a function reference, not a function call, to event props.
- Use an arrow function to pass extra arguments to a handler.
- React wraps native events in a SyntheticEvent for consistency.
๐ก Note: Writing `onClick={handleClick()}` calls the function immediately during render โ a common beginner mistake.
