Event handling in React
Event handling in React is similar to handling events in plain JavaScript — but with some key differences because React uses a synthetic event system (a lightweight wrapper over browser events for cross-browser consistency).
Vivek Rastogi
8/18/20251 min read
1. Basic Rules of Event Handling in React
Use camelCase for event names
Example: onClick, not onclick.Pass a function, not a string
Example: onClick={handleClick}, not onClick="handleClick()".Events receive an event object automatically
React gives you a SyntheticEvent, which behaves like a normal DOM event.
function App() {
function handleClick() {
alert("Button clicked!");
}
return (
<button onClick={handleClick}>Click Me</button>
);
}
The function handleClick is called when the button is clicked.
No need for () after the function name in JSX — otherwise it would run immediately instead of waiting for the event.
2. Passing Arguments to Event Handlers
If you need to send custom data:
function App() {
function handleClick(name) {
alert(`Hello, ${name}!`);
}
return (
<button onClick={() => handleClick("BB")}>
Greet
</button>
);
}
3. Event Handling with Inputs
For forms, you often use onChange:
import { useState } from "react";
function App() {
const [text, setText] = useState("");
function handleChange(event) {
setText(event.target.value);
}
return (
<div>
<input type="text" value={text} onChange={handleChange} />
<p>You typed: {text}</p>
</div>
);
}
onChange triggers whenever the input value changes.
The event object’s target.value gives the current input value.
4. Common React Events
onClick → Button clicks
onChange → Input, textarea changes
onSubmit → Form submission
onMouseEnter / onMouseLeave → Hover effects
onKeyDown / onKeyUp → Keyboard events
5. Preventing Default Behavior
Like in forms, to stop page refresh:
function App() {
function handleSubmit(event) {
event.preventDefault();
alert("Form submitted without reload!");
}
return (
<form onSubmit={handleSubmit}>
<button type="submit">Submit</button>
</form>
);
}
Key Takeaways
React wraps events into SyntheticEvent for cross-browser support.
Always use camelCase event names and pass functions, not strings.
Use arrow functions to pass parameters.
For forms, combine useState with event handlers to keep inputs controlled.