react-use-event-listeners
v1.0.1
Published
Handling the addEventListener(s) using the hooks.
Downloads
29
Maintainers
Readme
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