One of the key concepts in React is understanding how to handle events. In this article, we’ll take a closer look at SyntheticEvent, the unified event system in React that allows you to handle events in a consistent way across different browsers.
What is SyntheticEvent?
SyntheticEvent is a cross-browser wrapper around the native DOM event. It’s a lightweight, fast, and easy-to-use event system that’s built into React.
When you use an event handler in React, like onClick
or onChange
, you’re actually using SyntheticEvent under the hood. SyntheticEvent provides a consistent interface for handling events across different browsers, so you don’t have to worry about the differences in event handling between different browsers.
Using SyntheticEvent
Using SyntheticEvent is simple. When you attach an event handler to an element in your React component, like this:
<button onClick={handleClick}>Click me</button>
The event handler function handleClick
will receive a SyntheticEvent object as its first argument. This object contains information about the event, such as the type of event (e.g. click
, focus
, submit
), the target element that triggered the event, and the current value of the target element (if applicable).
You can access this information by destructuring the SyntheticEvent object in your event handler function:
function handleClick(event) {
const { type, target, value } = event;
console.log(type, target, value);
}
Tips for using SyntheticEvent
Here are a few tips for using SyntheticEvent in your React components:
- Don’t modify the SyntheticEvent object: The SyntheticEvent object is a read-only object, and you should not modify it. If you need to update the state of your component based on the event, use the
useState
Hook or thesetState
method in a class-based component. - Don’t rely on the event object outside of the event handler: The SyntheticEvent object is recycled for performance reasons, so you should not rely on the event object being available outside of the event handler function. If you need to use the event object outside of the handler, make a copy of it using the
event.persist()
method. - Use the
currentTarget
property instead of thetarget
property: Thetarget
property of the SyntheticEvent object refers to the element that originally dispatched the event, while thecurrentTarget
property refers to the element that the event listener is attached to. In most cases, you’ll want to use thecurrentTarget
property, as it will be the element that you’re interested in.
Conclusion
In this article, we learned about SyntheticEvent, the unified event system in React. We saw how to use SyntheticEvent to handle events in a consistent way across different browsers, and we looked at a few tips for using SyntheticEvent in your React components. With a solid understanding of SyntheticEvent, you’ll be well on your way to building great event-driven applications with React.
Exercises
To review these concepts, we will go through a series of exercises designed to test your understanding and apply what you have learned.
Write a functional component that uses SyntheticEvent to handle a form submission. The component should include a form with an input field and a submit button. When the form is submitted, the component should log the value of the input field to the console.
import React from 'react';
function FormExample() {
const handleSubmit = event => {
event.preventDefault();
const { target, type } = event;
const inputValue = target.elements.input.value;
console.log(type, inputValue);
};
return (
<form onSubmit={handleSubmit}>
<label>
Input:
<input type="text" name="input" />
</label>
<button type="submit">Submit</button>
</form>
);
}
Write a functional component that uses SyntheticEvent to handle a click event on a button. The component should include a button element and a counter that starts at 0. When the button is clicked, the component should increment the counter by 1.
import React, { useState } from 'react';
function ButtonExample() {
const [count, setCount] = useState(0);
const handleClick = event => {
const { type } = event;
setCount(prevCount => prevCount + 1);
console.log(type, count);
};
return (
<button onClick={handleClick}>
Clicked {count} times
</button>
);
}
Write a class-based component that uses SyntheticEvent to handle a change event on an input field. The component should include an input field and a state variable that stores the value of the input field. When the input field is changed, the component should update the state variable with the new value of the input field.
import React, { Component } from 'react';
class InputExample extends Component {
state = {
inputValue: '',
};
handleChange = event => {
const { type, target } = event;
const { value } = target;
this.setState({ inputValue: value });
console.log(type, value);
};
render() {
return (
<input
type="text"
value={this.state.inputValue}
onChange={this.handleChange}
/>
);
}
}
Write a functional component that uses SyntheticEvent to handle a hover event on a div element. The component should include a div element with a hover style that changes the background color of the div to red when the mouse is over the div, and back to white when the mouse is not over the div.
import React from 'react';
function DivExample() {
const [isHovered, setIsHovered] = React.useState(false);
const handleMouseOver = event => {
const { type } = event;
setIsHovered(true);
console.log(type, isHovered);
};
const handleMouseOut = event => {
const { type } = event;
setIsHovered(false);
console.log(type, isHovered);
};
return (
<div
style={{
backgroundColor: isHovered ? 'red' : 'white',
width: '100px',
height: '100px',
}}
onMouseOver={handleMouseOver}
onMouseOut={handleMouseOut}
/>
);
}
Write a class-based component that uses SyntheticEvent to handle a focus event on an input field. The component should include an input field and a state variable that tracks whether the input field is focused or not. When the input field is focused, the component should update the state variable to true. When the input field is blurred, the component should update the state variable to false.
import React, { Component } from 'react';
class InputExample extends Component {
state = {
isFocused: false,
};
handleFocus = event => {
const { type } = event;
this.setState({ isFocused: true });
console.log(type, this.state.isFocused);
};
handleBlur = event => {
const { type } = event;
this.setState({ isFocused: false });
console.log(type, this.state.isFocused);
};
render() {
return (
<input
type="text"
onFocus={this.handleFocus}
onBlur={this.handleBlur}
/>
);
}
}