npm

Ready to take your JavaScript development to the next level? Meet npm Enterprise - the ultimate in enterprise JavaScript.Learn more »

react-use-event-listeners

1.0.1 • Public • Published

Codecov

react-use-event-listeners

Handling the addEventListener(s) using the hooks.

Useful for listening to events that are not synthetic-events.


This hook is for one-EventTarget with multi event listeners, so not for multi-EventTargets with multi event listeners.

✨ Getting Started

with yarn

yarn add react-use-event-listeners

or

with npm

npm install react-use-event-listeners

💁 Usage

example component is count-up button app

import { useEventListeners } from 'react-use-event-listeners'
 
const CountUpApp = () => {
  const eventTargetRef = useRef(null)
  
  const countUp = useCallback(() => {
    setCount(prev => prev + 1)
  }, [])
 
  const handleOver = useCallback(() => {
    console.log('user will click count-up button')
  }, [])
 
  useEventListeners(
    {
      eventTarget: eventTargetRef.current,
      listeners: [
        ['click', countUp],
        ['pointerover', handleOver],
      ]
    },
    [eventTargetRef.current]
  )
 
  return (
    <>
      <div className="displayCount">{count}</div>
      <div className="countUpButton" ref={eventTargetRef}>
        Click then count up
      </div>
    </>
  )
}

🔥 APIs

useEventListeners(values, dependencyList)

name require type default decstiption
values Object - See below
dependencyList - Array - About React hooks 2nd argument array(DependencyList)

About the 1st argument object(values)

name require type default decstiption
eventTarget - EventTarget - MDN - EventTarget
listeners Array - README - register-event-listeners
What's listeners?

The listeners are the same format as dependency module register-event-listeners. Please refer to that document for details.

https://github.com/1natsu172/register-event-listeners#the-element-of-the-array

So, the 1st argument should be like this.
{
  eventTarget: eventTargetRef.current,
  listeners:[
    ['touchstart', onTouchStart, {capture: true, once: true}],
    ['touchmove', onTouchMove, { passive: false }],
    ['touchend', onEnd],
    ['touchcancel', onEnd]
  ]
}

💚 Running the tests

with Jest.

yarn test

or

npm run test

🏷 Versioning

Use SemVer for versioning. For the versions available, see the tags on this repository.

©️ License

MIT © 1natsu172

install

npm i react-use-event-listeners

Downloadsweekly downloads

0

version

1.0.1

license

MIT

homepage

github.com

repository

Gitgithub

last publish

collaborators

  • avatar
Report a vulnerability