React component for auto adding/removing event listeners during component life cycle.
Clone or download
Fetching latest commit…
Cannot retrieve the latest commit at this time.
Permalink
Type Name Latest commit message Commit time
Failed to load latest commit information.
.github
src
.babelrc.js
.eslintrc.js
.flowconfig
.gitignore
.pr-bumper.json
.travis.yml
CHANGELOG.md
CODE_OF_CONDUCT.md
CONTRIBUTING.md
LICENSE.md
README.md
jest-setup.js
jest.config.js
package.json
yarn.lock

README.md

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