Table of Content
Events in React are actions that a user does with a page. A user can click a button or type text inside a form.
React gives a way to handle these actions in code. React uses its own event system, and it works the same on all browsers.
Understand the Events in React
Events in React are based on the browser events, but they work with a layer called synthetic events. React uses this system to make sure events work the same way on all browsers.
A developer writes a handler, and React runs it when the action happens.
Here is an example:
function ButtonClick() {
function handleClick() {
alert('Button clicked');
}
return <button onClick={handleClick}>Click Me</button>;
}This example makes a button that shows a message when the user clicks it. React passes the click action to the handler. The handler runs and shows an alert.
The reason to use React events is that they give one way to handle actions in the app. They also work the same way across browsers, so you avoid browser bugs.
The Differences Between React Events and DOM Events
DOM events come from the browser and run inside the DOM tree. React events use synthetic events and run inside React’s own system. This gives React control over how events work.
Here is a table that shows you the key differences:
| React Events | DOM Events |
|---|---|
| Work directly in the browser DOM | Names use camelCase, like onClick |
| Names use lowercase, like onclick | Handler getsa synthetic event object |
| Handler gets a synthetic event object | Handler gets native event object |
| Same event system across browsers | Behavior can differ by browser |
Use DOM events when you work directly with the DOM. Use React events when you build a React app because React controls updates and rendering.
How to Bind Event Handlers in React
You can bind event handlers in React by using an inline arrow function or by binding in the constructor for class components. This makes sure the handler has the right this value.
class MyButton extends React.Component {
constructor(props) {
super(props);
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
console.log('Clicked');
}
render() {
return <button onClick={this.handleClick}>Click Me</button>;
}
}This code shows a class component. It binds the click handler inside the constructor. The button calls the handler when the user clicks it.
Passing Parameters to Event Handlers
You can pass data to an event handler by wrapping the handler in another function.
function ListItem({ id, onDelete }) {
return (
<li>
Item {id}
<button onClick={() => onDelete(id)}>Delete</button>
</li>
);
}This code shows a list item with a delete button. The button passes the item id to the delete handler. This way you know which item to delete.
Synthetic events wrap the browser’s native events. They have the same interface as the browser events but React manages them. Synthetic events work the same across browsers. This makes your code stable.
Examples
Click Event with State Change:
function Counter() {
const [count, setCount] = React.useState(0);
function addOne() {
setCount(count + 1);
}
return <button onClick={addOne}>Count: {count}</button>;
}This example shows a button with a count. The user clicks the button, and the count goes up by one. The event handler updates the state, and React shows the new count.
Form Input Change Event:
function NameInput() {
const [name, setName] = React.useState('');
function handleChange(e) {
setName(e.target.value);
}
return (
<div>
<input type="text" onChange={handleChange} />
<p>Your name: {name}</p>
</div>
);
}This example shows an input box. The user types inside it. The event handler takes the new text and sets it into the state. React updates the page with the new text.
Prevent Default with Form Submit:
function MyForm() {
function handleSubmit(e) {
e.preventDefault();
alert('Form submitted');
}
return (
<form onSubmit={handleSubmit}>
<button type="submit">Send</button>
</form>
);
}This example shows a form with a submit button. The handler stops the default browser action and shows an alert instead. This is how you handle form submits in React.
Advanced Event Handling with Multiple Buttons:
function ActionButtons() {
function handleAction(action) {
alert('Action: ' + action);
}
return (
<div>
<button onClick={() => handleAction('save')}>Save</button>
<button onClick={() => handleAction('delete')}>Delete</button>
</div>
);
}This example shows two buttons. Each button passes a different value to the handler. The handler shows which action the user chose. This is useful for advanced UI events.
Wrapping Up
You learned about events and how they work. You also saw how React events differ from DOM events, how to bind handlers, how to pass parameters, and how to use synthetic events.
Here is a quick recap:
- React events give one system for user actions.
- React events use synthetic events to work the same on all browsers.
- You can bind handlers in different ways.
- You can pass parameters to handlers and prevent default actions.
FAQs
How do I handle onClick events in React?
- Attach the event handler using the JSX attribute
<button onClick>. - Use a function to define the action inside the component.
import React from 'react';
function MyButton() {
function handleClick() {
alert('Button clicked');
}
return <button onClick={handleClick}>Click Me</button>;
}
export default MyButton;
What is the difference between React events and DOM events?
- React wraps native browser events into
SyntheticEventfor cross-browser consistency. - React event names use camelCase like
onClickinstead of lowercase likeonclick.
How can I pass parameters to event handlers in React?
- Use an arrow function inside the event attribute to pass parameters.
function User({ name }) {
function greet(userName) {
alert('Hello ' + userName);
}
return <button onClick={() => greet(name)}>Greet</button>;
}
How do I prevent default behavior in React events?
- Call
event.preventDefault()inside the handler.
function MyForm() {
function handleSubmit(event) {
event.preventDefault();
alert('Form submitted');
}
return (
<form onSubmit={handleSubmit}>
<button type="submit">Submit</button>
</form>
);
}
Similar Reads
React Lists and Keys help you show many items and keep each item tracked for updates. What do Lists and…
Rendering HTML in React might sound like a complicated task, but it’s actually quite simple once you understand the basics.…
In this introduction, you will understand what React JS is and learn how to use NPM commands to get started…
Forms in React allow a page to take data from a user. A developer uses them to show fields, take…
JSX helps write React UI with HTML-like syntax. It links JavaScript logic with markup in one view. What is JSX…
Through this article, you will learn how to install React on common operating systems such as Windows, macOS, and Ubuntu.…
Props in React pass data from one part to another part. They let you build parts that reuse data and…
In this tutorial, you will learn what components are in React and how to build them. Also, how to pass…
State in React lets a component hold data that can change over time. You can use it to track values…
React conditional rendering is a way to show different parts of a page. Click here to see how it works…