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., onClick not onclick)
  • You pass functions, not strings, as handlers

πŸ’‘ React events are designed to work identically across all browsers.


πŸ”§ Key Differences (React vs HTML)

HTMLReact
onclick="handleClick()"onClick={handleClick}
String-basedFunction-based
LowercaseCamelCase
Native DOM eventsReact SyntheticEvent

βœ… Basic Event Handling Example

πŸ” Explanation:

  • onClick is the event
  • handleClick is the function that gets called when the event happens

πŸ” List of Common React Events

Event TypeReact PropTriggered When...
ClickonClickElement is clicked
ChangeonChangeForm field value changes
SubmitonSubmitForm is submitted
Mouse EnteronMouseEnterMouse enters an element
Mouse LeaveonMouseLeaveMouse leaves an element
Key DownonKeyDownKey is pressed down
FocusonFocusElement receives focus
BluronBlurElement 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 referenceAvoid calling directly (onClick={func()})
Use preventDefault() for formsDon’t let forms reload the page
Use arrow functions to pass argsAvoid inline logic in JSX

πŸ“Œ Summary

FeatureDescription
Event NameUse camelCase like onClick, onChange
Event HandlerPass a function (not a string)
Event ObjectAccess via e in function
Custom ArgsUse arrow functions to pass arguments
SyntheticEventReact’s cross-browser wrapper for DOM events