React Event Listener
react-event-listener is a lightweight React component that offers a declarative way to manage global DOM event listeners, specifically targeting `window` and `document`. It leverages React's component lifecycle to automatically bind and unbind events, preventing common memory leaks and simplifying event management for global scopes. The current stable version is `0.6.7`, and releases are infrequent, primarily focused on maintenance and compatibility updates rather than new features, indicating a mature and stable library. A key differentiator is its `withOptions` utility, allowing developers to configure standard `addEventListener` options like `passive` and `capture` declaratively. It aims to solve the problem of imperatively adding and removing global event listeners by integrating them seamlessly into the React component tree.
Common errors
-
React TestUtils.Simulate.event() does not bubble up to window or document.
cause React's `TestUtils.Simulate` methods only simulate events on the component itself and do not propagate to global DOM elements like `window` or `document`.fixFor testing global event listeners, use native DOM event dispatching methods such as `document.dispatchEvent(new Event('event-name'))` or `window.dispatchEvent(new Event('event-name'))` to accurately simulate global events.
Warnings
- gotcha Avoid using inline functions for event listeners passed to EventListener components.
- gotcha When performing Server-Side Rendering (SSR), `window` and `document` objects are not available.
Install
-
npm install react-event-listener -
yarn add react-event-listener -
pnpm add react-event-listener
Imports
- EventListener
const EventListener = require('react-event-listener');import EventListener from 'react-event-listener';
- withOptions
import withOptions from 'react-event-listener';
import { withOptions } from 'react-event-listener'; - Target Type
import EventListener from 'react-event-listener';
Quickstart
import React, { Component } from 'react';
import EventListener, { withOptions } from 'react-event-listener';
import ReactDOM from 'react-dom';
class MyComponent extends Component {
handleResize = () => {
console.log('Window resized!');
};
handleScroll = () => {
// This will only log if scroll is detected due to passive: true
console.log('Window scrolled (passive)!');
};
handleKeyDown = (event) => {
if (event.key === 'Escape') {
console.log('Escape key pressed on document (capture)!');
}
};
render() {
return (
<div>
<h1>Global Event Listener Example</h1>
<p>Open your console and try resizing the window, scrolling, or pressing 'Escape'.</p>
<div style={{ height: '200vh', background: 'lightgray', padding: '20px' }}>
Scrollable content to trigger window scroll.
<p>This div ensures the page is tall enough to scroll.</p>
</div>
<EventListener
target="window"
onResize={this.handleResize}
onScroll={withOptions(this.handleScroll, { passive: true, capture: false })}
/>
<EventListener target={document} onKeyDownCapture={this.handleKeyDown} />
</div>
);
}
}
// Assuming a root element with id 'root' exists in your HTML
ReactDOM.render(<MyComponent />, document.getElementById('root'));