React Event Handling
In React, events are handled similarly to DOM events in plain JavaScript, but with a few key differences that make them more powerful and consistent across browsers.
What are React Events?
In React, events are just like HTML DOM events (like click, submit, change, etc.), but they're handled a bit differently.
Instead of using lowercase (like in HTML: onclick), React uses camelCase (onClick). And instead of using strings, you pass a function.
A React Event is an object that represents an interaction from the user, like:- Clicking a button (
onClick
) - Typing into an input (
onChange
) - Submitting a form (
onSubmit
) - Moving the mouse (
onMouseMove
) - Focusing or blurring a field (
onFocus
,onBlur
)
Handling Click Event
onClick={handleClick}
– Tells React to call the handleClick function when the button is clicked.- No need to use addEventListener. React handles it behind the scenes.
Handling Input Change Event
onChange={handleChange}
– React calls this function when the input changes.- event.target.value – Gives the current text inside the input.
What is SyntheticEvent?
In React, every event you use (like onClick, onChange) gets passed a special object called SyntheticEvent
— it wraps the browser's native event for cross-browser consistency.
onChange
– Updates text as you type.onClick
– Reacts to button click.onSubmit
– Handles form submission.event.preventDefault()
– Stops the form from refreshing the page.
Summary
- React uses camelCase for event names (onClick, onSubmit, etc.)
- Event handlers are passed as functions
- React wraps native events in a SyntheticEvent
- Prevent default browser behavior using e.preventDefault()