React Event Listener

0.6.7 · maintenance · verified Sun Apr 19

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

Warnings

Install

Imports

Quickstart

This example demonstrates how to use EventListener to bind to global 'window' resize and scroll events, and 'document' keydown events, including the use of `withOptions` for event configuration.

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'));

view raw JSON →