In React.js, an event is an object that represents an action or occurrence, such as a user interaction (e.g., a mouse click, a key press, or a form submission). React handles events in a declarative and efficient way, providing a synthetic event system that is consistent across different browsers.
Key Features of Events in React:
Synthetic Events: React wraps native browser events in its own event system called SyntheticEvent. This ensures compatibility across browsers and provides additional features like event pooling for performance optimization.
Event Handling:
- Events in React are written as camelCase (e.g.,
onClick,onChange), unlike plain HTML where events are written in lowercase (e.g.,onclick,onchange). - Event handlers are passed as functions, typically as references or inline arrow functions.
- Events in React are written as camelCase (e.g.,
Binding
this:- When using class components, you may need to bind the event handler to the component instance (
this). - In function components, this is not required, especially when using hooks like
useStateoruseReducer.
- When using class components, you may need to bind the event handler to the component instance (
Prevent Default Behavior:
- Use
event.preventDefault()to prevent the default action of an event (e.g., stopping a form from submitting).
- Use
Stop Propagation:
- Use
event.stopPropagation()to stop the event from bubbling up to parent elements.
- Use
Example of Event Handling in React:
Functional Component Example:
Class Component Example:
Common Events in React:
| Event Name | Description |
|---|---|
onClick | Triggered when an element is clicked. |
onChange | Triggered when the value of an input changes. |
onSubmit | Triggered when a form is submitted. |
onMouseEnter | Triggered when the mouse enters an element. |
onMouseLeave | Triggered when the mouse leaves an element. |
onKeyDown | Triggered when a key is pressed down. |
onKeyUp | Triggered when a key is released. |
onFocus | Triggered when an element gains focus. |
onBlur | Triggered when an element loses focus. |
React's event system is designed to be intuitive, efficient, and cross-browser compatible, making it easier to build interactive UIs.
Comments
Post a Comment