React Events
Handling user interactions in React
⚡ What are React Events?
Events are actions triggered by users like clicks, typing, or hovering. React handles events using camelCase syntax and passes functions as event handlers, making interactive UIs simple and intuitive to build.
function Button() {
const handleClick = () => alert('Clicked!');
return <button onClick={handleClick}>Click Me</button>;
}
Common React Events
Click Events
Handle button and element clicks
onClick={handleClick}
Input Events
Capture user typing and changes
onChange={handleChange}
Form Events
Handle form submissions
onSubmit={handleSubmit}
Mouse Events
Track mouse movements and hovers
onMouseEnter={handleHover}
🔹 Basic Click Event
The onClick event is the most common event in React. Pass a function reference (not a function call) to the onClick prop.
function ClickButton() {
const handleClick = () => {
alert('Button was clicked!');
};
return (
<button onClick={handleClick}>
Click Me
</button>
);
}
// ❌ Wrong: onClick={handleClick()}
// ✅ Correct: onClick={handleClick}
Output:
Click the button to see the alert
🔹 Event with State Update
Events often update component state. Use the useState hook to manage state and update it in event handlers.
import { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
const increment = () => {
setCount(count + 1);
};
return (
<div>
<h2>Count: {count}</h2>
<button onClick={increment}>Increment</button>
</div>
);
}
Output:
Count: 0
Click to increase count
🔹 Input Change Event
The onChange event captures input changes. Access the input value using event.target.value to create controlled components.
import { useState } from 'react';
function NameInput() {
const [name, setName] = useState('');
const handleChange = (event) => {
setName(event.target.value);
};
return (
<div>
<input
type="text"
value={name}
onChange={handleChange}
placeholder="Enter your name"
/>
<p>Hello, {name || 'Guest'}!</p>
</div>
);
}
Output:
Hello, Guest!
Type to see your name appear
🔹 Form Submit Event
Handle form submissions with onSubmit. Always call event.preventDefault() to stop the default form submission behavior.
import { useState } from 'react';
function LoginForm() {
const [email, setEmail] = useState('');
const handleSubmit = (event) => {
event.preventDefault(); // Prevent page reload
alert(`Submitted: ${email}`);
};
return (
<form onSubmit={handleSubmit}>
<input
type="email"
value={email}
onChange={(e) => setEmail(e.target.value)}
placeholder="Enter email"
/>
<button type="submit">Submit</button>
</form>
);
}
Output:
🔹 Multiple Event Handlers
Components can have multiple event handlers for different interactions. Each handler manages its own specific behavior.
import { useState } from 'react';
function InteractiveButton() {
const [message, setMessage] = useState('Hover or click me!');
const handleClick = () => {
setMessage('Button clicked!');
};
const handleMouseEnter = () => {
setMessage('Mouse is hovering!');
};
const handleMouseLeave = () => {
setMessage('Mouse left!');
};
return (
<div>
<button
onClick={handleClick}
onMouseEnter={handleMouseEnter}
onMouseLeave={handleMouseLeave}
>
Interactive Button
</button>
<p>{message}</p>
</div>
);
}
Output:
Hover or click me!
🔹 Passing Arguments to Event Handlers
To pass arguments to event handlers, wrap them in an arrow function or use the bind method.
function ButtonList() {
const handleClick = (buttonName) => {
alert(`You clicked ${buttonName}`);
};
return (
<div>
<button onClick={() => handleClick('Button 1')}>
Button 1
</button>
<button onClick={() => handleClick('Button 2')}>
Button 2
</button>
<button onClick={() => handleClick('Button 3')}>
Button 3
</button>
</div>
);
}
Output:
🔹 Event Object
React passes a synthetic event object to event handlers. Use it to access event properties and methods.
function EventInfo() {
const handleClick = (event) => {
console.log('Event type:', event.type);
console.log('Target element:', event.target);
console.log('Mouse position:', event.clientX, event.clientY);
};
return (
<button onClick={handleClick}>
Click to see event info in console
</button>
);
}
Output:
Check browser console for details
🔹 React vs HTML Events
React events differ slightly from standard HTML events:
Key Differences:
- Naming: React uses camelCase (onClick) vs HTML lowercase (onclick)
- Function: React passes function reference vs HTML uses string
- Prevent Default: Must call event.preventDefault() explicitly
- Synthetic Events: React wraps native events for consistency
Examples:
// HTML
<button onclick="handleClick()">Click</button>
// React
<button onClick={handleClick}>Click</button>