How to Use Synthetic Events in React
React uses a cross-browser wrapper called SyntheticEvents to ensure consistent event handling across all major browsers. This article covers the fundamentals of React Synthetic Events, explains how they differ from native browser events, and provides practical code examples to help you implement them in your projects.
What is a Synthetic Event?
A Synthetic Event is a cross-browser wrapper around the browser’s
native event. It has the same interface as the native browser event,
including methods like preventDefault() and
stopPropagation(), but works identically across all
browsers.
React implements this wrapper to normalize behaviors so that you do not have to write custom code for different browsers.
Basic Implementation of Synthetic Events
To implement a Synthetic Event in React, you define an event handler
function and pass it as an attribute to a JSX element. React event
attributes are named using camelCase (e.g.,
onClick, onChange, onSubmit)
instead of lowercase.
Here is a basic example of implementing a click event:
import React from 'react';
function ClickButton() {
const handleClick = (event) => {
// 'event' is the SyntheticEvent object
console.log('Button clicked!', event.target);
};
return (
<button onClick={handleClick}>
Click Me
</button>
);
}
export default ClickButton;In the example above, React automatically passes the
SyntheticEvent object as the first argument
(event) to the handleClick function.
Handling Form Inputs with Synthetic Events
Synthetic Events are commonly used to handle user input in form
fields using the onChange event handler.
import React, { useState } from 'react';
function UserForm() {
const [inputValue, setInputValue] = useState('');
const handleInputChange = (event) => {
// Accessing the native input value through the synthetic event
setInputValue(event.target.value);
};
const handleSubmit = (event) => {
// Preventing the default browser form submission behavior
event.preventDefault();
alert(`Submitted Value: ${inputValue}`);
};
return (
<form onSubmit={handleSubmit}>
<input
type="text"
value={inputValue}
onChange={handleInputChange}
/>
<button type="submit">Submit</button>
</form>
);
}
export default UserForm;Key Differences to Keep in Mind
When implementing Synthetic Events, remember these key differences from vanilla JavaScript:
- CamelCase Naming: React uses
onClickandonChangeinstead of HTML’sonclickandonchange. - Pass Functions, Not Strings: In JSX, you pass the
actual function reference (e.g.,
onClick={handleClick}) rather than a string (e.g.,onclick="handleClick()"). - Preventing Default Behavior: You cannot return
falseto prevent default behavior in React. You must explicitly callevent.preventDefault(). - Accessing Native Events: If you ever need to access
the underlying browser event for a specific integration, you can access
it via
event.nativeEvent.