Skip to content

React component for auto adding/removing event listeners during component life cycle.

License

Notifications You must be signed in to change notification settings

dogma-io/react-domlistener

Repository files navigation

react-domlistener NPM Coverage

React component for auto adding/removing event listeners during component life cycle.

Table of Contents

Installation

npm

npm install react-domlistener

yarn

yarn add react-domlistener

Documentation

This project exports a component, DOMListener, which serves the purpose of auto adding/removing an event listener during the life cycle of a React component. One of the advantages to using this component over manually using addEventListener/removeEventListener yourself is that you don't have to worry about cases where you forget to remove. When forgetting to remove event listeners you create memory leaks, which can be difficult to track down.

Below is an example of how to use react-domlistener.

import {DOMListener} from 'react-domlistener'

export default class FooBar extends React.Component {
  _handleWindowResize = (e) => {
    // TODO: do something clever on window resize
  }

  render() {
    return (
      <div className="foo-bar">
        <DOMListener
          listener={this._handleWindowResize}
          target={window}
          type="resize"
        />
      </div>
    )
  }
}

NOTE: This project requires at a minimum React version 16.3.0 as it depends on newer API methods introduced in this version.

Code of Conduct

Please see the code of conduct.

Contributing

Please see the contributing guide.

License

MIT

About

React component for auto adding/removing event listeners during component life cycle.

Resources

License

Code of conduct

Stars

Watchers

Forks

Packages

No packages published