In a React application, managing events is made easy with React’s built-in event handling system. Say goodbye to using addEventListener
! In this article, we will explore how to interact with events in React.
Event Handling in React
Event handling in React is similar to handling events in plain old JavaScript, with a few key differences. Let’s consider the following example from a previous article about managing state in React:
const CurrencySwitcher = props => {
return (
<button onClick={props.handleChangeCurrency}>
Current currency is {props.currency}. Change it!
</button>
);
};
As you can see, the event handler handleChangeCurrency
is passed as a prop to the onClick
event. This is similar to using JavaScript event handlers in HTML, except that everything is defined in JavaScript rather than in HTML, and you’re passing a function instead of a string.
Although the event names are similar to JavaScript event names, there is a slight difference in naming conventions. In React, event names use camelCase, so onclick
becomes onClick
and onsubmit
becomes onSubmit
.
For reference, here’s an example of old school HTML with JavaScript events mixed in:
<button onclick="handleChangeCurrency()">...</button>
Event Handlers as Methods
In React, it’s a convention to have event handlers defined as methods on the Component class. Here’s an example:
class Converter extends React.Component {
handleChangeCurrency = event => {
this.setState({ currency: this.state.currency === '€' ? '$' : '€' });
}
}
All event handlers in React receive an event object that adheres to the W3C UI Events specification, ensuring cross-browser compatibility.
Binding this
in Methods
When defining methods in React components, it’s important to remember to bind this
. By default, methods in ES6 classes are not bound, meaning that this
is not defined unless you define methods as arrow functions. Here’s an example:
class Converter extends React.Component {
handleClick = e => {
/* ... */
}
// ...
}
In order to ensure this
is properly bound when using the property initializer syntax with Babel (which is enabled by default in create-react-app
), you don’t need to manually bind this
. However, if you’re not using this syntax, you must manually bind this
in the constructor, like so:
class Converter extends React.Component {
constructor(props) {
super(props);
this.handleClick = this.handleClick.bind(this);
}
handleClick(e) {
/* ... */
}
}
Events Supported in React
React supports a wide range of events that you can use in your applications. Here’s a summary list of the events supported:
- Clipboard: onCopy, onCut, onPaste
- Composition: onCompositionEnd, onCompositionStart, onCompositionUpdate
- Keyboard: onKeyDown, onKeyPress, onKeyUp
- Focus: onFocus, onBlur
- Form: onChange, onInput, onSubmit
- Mouse: onClick, onContextMenu, onDoubleClick, onDrag, onDragEnd, onDragEnter, onDragExit, onDragLeave, onDragOver, onDragStart, onDrop, onMouseDown, onMouseEnter, onMouseLeave, onMouseMove, onMouseOut, onMouseOver, onMouseUp
- Selection: onSelect
- Touch: onTouchCancel, onTouchEnd, onTouchMove, onTouchStart
- UI: onScroll
- Mouse Wheel: onWheel
- Media: onAbort, onCanPlay, onCanPlayThrough, onDurationChange, onEmptied, onEncrypted, onEnded, onError, onLoadedData, onLoadedMetadata, onLoadStart, onPause, onPlay, onPlaying, onProgress, onRateChange, onSeeked, onSeeking, onStalled, onSuspend, onTimeUpdate, onVolumeChange, onWaiting
- Image: onLoad, onError
- Animation: onAnimationStart, onAnimationEnd, onAnimationIteration
- Transition: onTransitionEnd
With the flexibility and power of React’s event handling system, you can easily build interactive and dynamic applications.