Handling Events
35 minHandling events with React elements is very similar to handling events on DOM elements.
React events are named using camelCase, rather than lowercase.
With JSX you pass a function as the event handler, rather than a string.
React uses SyntheticEvent, a cross-browser wrapper around the native event, ensuring consistent behavior across different browsers.
Event handlers receive the SyntheticEvent as their argument, which has the same interface as native events but works identically across all browsers.
You can prevent default behavior using event.preventDefault() and stop propagation with event.stopPropagation(), just like with native events.
Key Concepts
- React events use camelCase naming (onClick, not onclick).
- Event handlers are passed as functions, not strings.
- SyntheticEvent provides cross-browser compatibility.
- Event handlers can access the event object for default prevention and propagation control.
- Arrow functions are commonly used for inline event handlers.
Learning Objectives
Master
- Writing event handlers in React components
- Understanding SyntheticEvent and its properties
- Preventing default behavior and stopping propagation
- Passing parameters to event handlers
Develop
- Event-driven programming patterns in React
- Understanding React's event system abstraction
- Best practices for event handler organization
Tips
- Use arrow functions for inline handlers when you need to pass parameters.
- Extract complex event handlers into separate functions for readability.
- Use event.preventDefault() to prevent form submissions and link navigation.
- Consider using useCallback for event handlers passed to child components.
Common Pitfalls
- Calling the function immediately instead of passing it (onClick={handleClick()} vs onClick={handleClick}).
- Not preventing default behavior when needed (e.g., form submissions).
- Forgetting to bind 'this' in class components (not needed in functional components).
- Creating new function instances on every render without useCallback.
Summary
- React events use camelCase and pass functions as handlers.
- SyntheticEvent provides consistent cross-browser event handling.
- Event handlers can prevent default behavior and stop propagation.
- Arrow functions are convenient for inline event handlers.
Exercise
Create a button that shows an alert when clicked.
function AlertButton() {
const handleClick = () => {
alert('Button clicked!');
};
return <button onClick={handleClick}>Click Me</button>;
}
Exercise Tips
- Extract the handler function for better readability.
- Add event parameter if you need to access event properties.
- Consider adding loading state for async operations.
- Test with keyboard navigation (Enter/Space keys).