Event Handling
Subject: React
π§© What Are Events in React?
Events in React are just like events in regular HTML (e.g., click, submit, change), but with a few key differences:
- React wraps events in a synthetic event system (
SyntheticEvent) - Uses camelCase instead of lowercase (e.g., 
onClicknotonclick) - You pass functions, not strings, as handlers
 
π‘ React events are designed to work identically across all browsers.
π§ Key Differences (React vs HTML)
| HTML | React | 
|---|---|
onclick="handleClick()" | onClick={handleClick} | 
| String-based | Function-based | 
| Lowercase | CamelCase | 
| Native DOM events | React SyntheticEvent | 
β Basic Event Handling Example
π Explanation:
onClickis the eventhandleClickis the function that gets called when the event happens
π List of Common React Events
| Event Type | React Prop | Triggered When... | 
|---|---|---|
| Click | onClick | Element is clicked | 
| Change | onChange | Form field value changes | 
| Submit | onSubmit | Form is submitted | 
| Mouse Enter | onMouseEnter | Mouse enters an element | 
| Mouse Leave | onMouseLeave | Mouse leaves an element | 
| Key Down | onKeyDown | Key is pressed down | 
| Focus | onFocus | Element receives focus | 
| Blur | onBlur | Element loses focus | 
π§ͺ Example: Form Input with onChange
β‘οΈ e.target.value gives the current value of the input field.
π₯ Example: Form Submit with onSubmit
βοΈ Passing Arguments to Event Handlers
π§ React SyntheticEvent
React wraps all browser events in a SyntheticEvent to ensure consistency across browsers.
π Event Handling Best Practices
| β Do's | β Don'ts | 
|---|---|
| Use camelCase (onClick, onSubmit) | Avoid lowercase (onclick) | 
| Pass a function reference | Avoid calling directly (onClick={func()}) | 
Use preventDefault() for forms | Donβt let forms reload the page | 
| Use arrow functions to pass args | Avoid inline logic in JSX | 
π Summary
| Feature | Description | 
|---|---|
| Event Name | Use camelCase like onClick, onChange | 
| Event Handler | Pass a function (not a string) | 
| Event Object | Access via e in function | 
| Custom Args | Use arrow functions to pass arguments | 
| SyntheticEvent | Reactβs cross-browser wrapper for DOM events | 
Advertisement Slot 1
Advertisement Slot 2