Introduction
In React, event handling works similarly to JavaScript DOM events, but React uses a slightly different syntax and provides better performance through a system called Synthetic Events.
In this tutorial, you will learn what event handling is, why it is used, syntax, examples, real-life use cases, common mistakes, interview questions, and best practices.
What is Event Handling in React?
Event handling in React is the process of responding to user actions or browser events inside React components.
Whenever users interact with the UI, React can execute functions called event handlers.
- Use meaningful function names
- Keep handlers small
- Avoid unnecessary inline functions
- Use separate functions for readability
- Use preventDefault() when necessary
- Reuse event handlers when possible
Examples of Events
Some common React events are:
- Click events
- Change events
- Submit events
- Mouse events
- Keyboard events
Why Event Handling is Used in React?
Event handling is used because modern applications need user interaction.
Examples:
- Clicking buttons
- Filling forms
- Searching products
- Opening menus
- Playing videos
All these interactions require event handling.
Features of Event Handling in React
1. Interactive Applications
Makes applications dynamic and responsive.
2. Easy Syntax
React provides clean event handling syntax.
3. Reusable Functions
Event handlers can be reused.
4. Better Performance
React uses Synthetic Events for optimized performance.
Syntax of Event Handling in React
Basic syntax:
<button onClick={handleClick}>
Click
</button>
Understanding the Syntax
onClick: React event name.
handleClick: Function executed when the event occurs.
Simple Example of Event Handling
function App() {
function handleClick() {
alert("Button Clicked");
}
return (
<button onClick={handleClick}>
Click Me
</button>
);
}
export default App;
Output
When the button is clicked:
React Events Naming Convention
React events use camelCase.
| HTML | React |
|---|---|
onclick |
onClick |
onchange |
onChange |
onsubmit |
onSubmit |
Passing Arguments in Event Handling
Arguments can be passed inside event handlers.
Example
function App() {
function greet(name) {
alert("Hello " + name);
}
return (
<button onClick={() => greet("Gaurav")}>
Click
</button>
);
}
Output
Event Handling with useState
Event handling is commonly used with state management.
Example
import { useState } from "react";
function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<h1>{count}</h1>
<button onClick={() => setCount(count + 1)} > Increment </button>
</div>
);
}
Output
onChange Event in React
onChange handles input field changes.
Example
import { useState } from "react";
function App() {
const [name, setName] = useState("");
return (
<div>
<input type="text" onChange={(e) => setName(e.target.value) } />
<h1>{name}</h1>
</div>
);
}
Output
onSubmit Event in React
onSubmit handles form submissions.
Example
function App() {
function handleSubmit(event) {
event.preventDefault();
alert("Form Submitted");
}
return (
<form onSubmit={handleSubmit}>
<button type="submit">
Submit
</button>
</form>
);
}
Why preventDefault() is Used?
By default, forms reload the page after submission.
preventDefault() stops this behavior.
Mouse Events in React
React supports multiple mouse events.
Examples:
- onClick
- onDoubleClick
- onMouseOver
- onMouseOut
Example:
function App() {
function showMessage() {
alert("Mouse Over");
}
return (
<h1 onMouseOver={showMessage}>
Hover Here
</h1>
);
}
Keyboard Events in React
Keyboard events handle typing actions.
Examples:
- onKeyDown
- onKeyUp
- onKeyPress
Example:
function App() {
function handleKey() {
alert("Key Pressed");
}
return (
<input type="text" onKeyDown={handleKey} />
);
}
Synthetic Events in React
React uses Synthetic Events instead of direct browser events.
Synthetic Events:
- Work consistently across browsers
- Improve performance
- Provide better compatibility
Real-Life Example of Event Handling
Suppose you are building an e-commerce website.
Event handling manages:
- Add to cart button
- Search bar
- Login form
- Product filters
- Wishlist buttons
Without event handling, these features would not work.
Inline Event Handling
Functions can be written directly inside JSX.
Example:
<button onClick={() => alert("Hello")}>
Click
</button>
Separate Function Event Handling
Using separate functions improves readability.
Example:
function App() {
function handleClick() {
alert("Clicked");
}
return (
<button onClick={handleClick}>
Click
</button>
);
}
Difference Between HTML and React Event Handling
| Feature | HTML | React |
|---|---|---|
| Event Naming | lowercase | camelCase |
| Syntax | String | JavaScript Function |
| Prevent Default | Manual | event.preventDefault() |
Advantages of Event Handling in React
| Feature | Benefit |
|---|---|
| Interactive UI | Better user experience |
| Dynamic Updates | Real-time interaction |
| Reusable Handlers | Cleaner code |
| Synthetic Events | Better performance |
| Easy Integration | Works with state and props |
Common Mistakes in React Event Handling
1. Calling Function Immediately
Wrong:
<button onClick={handleClick()}>
Click
</button>
Correct:
<button onClick={handleClick}>
Click
</button>
2. Forgetting Arrow Function for Arguments
Wrong:
<button onClick={greet("Gaurav")}>
Correct:
<button onClick={() => greet("Gaurav")}>
3. Not Using preventDefault()
Forms reload unexpectedly without it.
4. Writing Large Inline Functions
Large inline functions reduce readability.
5. Incorrect Event Names
Wrong:
onclick
Correct:
onClick
Event Handling with Props
Parent components can pass event handlers as props.
Example:
function Button(props) {
return (
<button onClick={props.clickHandler}>
Click
</button>
);
}
function App() {
function showMessage() {
alert("Hello");
}
return (
<Button clickHandler={showMessage} />
);
}
Real-World Applications of Event Handling
Event handling is heavily used in:
- Social media apps
- Banking apps
- E-commerce websites
- Chat applications
- Admin dashboards
Examples:
- Button clicks
- Search filters
- Form validation
- Notifications
- Menu toggles
Conclusion
Event Handling is one of the most important concepts in React because it makes applications interactive and dynamic. It allows developers to respond to user actions efficiently using clean and reusable code.
React simplifies event handling with:
- CamelCase syntax
- Synthetic Events
- Easy integration with state and props