Events in React
React handles events similarly to HTML, but with some differences: event names are camelCase (onClick, onChange, onSubmit), and you pass functions as event handlers, not strings.
The event object in React is a SyntheticEvent — a cross-browser wrapper around the native event. It has the same interface as native events (preventDefault, stopPropagation, target, etc.).
Example
function EventExamples() {
function handleClick(e) {
e.preventDefault();
console.log('Button clicked!');
}
function handleChange(e) {
console.log('Input value:', e.target.value);
}
function handleSubmit(e) {
e.preventDefault();
console.log('Form submitted!');
}
return (
<div>
<button onClick={handleClick}>Click Me</button>
<input onChange={handleChange} placeholder="Type here" />
<form onSubmit={handleSubmit}>
<button type="submit">Submit</button>
</form>
</div>
);
} - onClick — Fires when an element is clicked
- onChange — Fires when input value changes
- onSubmit — Fires when a form is submitted
- onMouseEnter / onMouseLeave — Fires on hover
- onKeyDown / onKeyUp — Fires on keyboard input
- Use e.preventDefault() to prevent default browser behavior
Notes
- Pass the function reference (onClick={handleClick}), not a function call (onClick={handleClick()}). The second form would execute immediately on render.
