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.
with yarn
yarn add react-use-event-listeners
or
with npm
npm install react-use-event-listeners
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>
</>
)
}
name | require | type | default | decstiption |
---|---|---|---|---|
values | ✓ | Object | - | See below |
dependencyList | - | Array | - | About React hooks 2nd argument array(DependencyList) |
name | require | type | default | decstiption |
---|---|---|---|---|
eventTarget | - | EventTarget | - | MDN - EventTarget |
listeners | ✓ | Array | - | README - register-event-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
{
eventTarget: eventTargetRef.current,
listeners:[
['touchstart', onTouchStart, {capture: true, once: true}],
['touchmove', onTouchMove, { passive: false }],
['touchend', onEnd],
['touchcancel', onEnd]
]
}
with Jest.
yarn test
or
npm run test
Use SemVer for versioning. For the versions available, see the tags on this repository.
MIT © 1natsu172