use-typed-event-listener
v4.0.2
Published
React Hook for DOM event listeners with TypeScript supported
Downloads
15,946
Maintainers
Readme
use-typed-event-listener
use-typed-event-listener
is a React Hook for DOM event listeners with TypeScript supported
With TypeScript helps, this package can detect which event type the element supports, and automatically cast a correct typing for event
Installation
npm install use-typed-event-listener
# or
yarn add use-typed-event-listener
Interface
useEventListener(element, eventType, listener[, options])
element
can bewindow
,document
or anyHTMLElement
. If it isundefined
, no event will not be boundeventType
is a case-sensitive string representing the event type to listen forlistener
is the callback function when an event ofeventType
occursoptions
(optional) see https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener#Parameters
Usage
listener
typings will be automatically casted based onelement
andeventType
import useEventListener from 'use-typed-event-listener' export default (props: Props) => { // typings for `event` will be `MouseEvent` as this package recognizes the `click` event type useEventListener(window, 'click', (event) => { console.log(event.buttons) }) return <SomeComponent /> }
No need to avoid passing new reference to
listener
oroptions
, they are memorized and will not trigger the hook againimport useEventListener from 'use-typed-event-listener' export default (props: Props) => { // this hook will only run once useEventListener(window, 'click', (event) => {}, { capture: true, }) return <SomeComponent /> }
Prevent casting
eventType
asstring
import useEventListener from 'use-typed-event-listener' export default (props: Props) => { const eventType: string = 'click' useEventListener(window, eventType, (event) => { // as `eventType` is a wild card string, `event` will fallback to general `Event` type // this line will throw `Property 'buttons' does not exist on type 'Event'.ts(2339)` console.log(event.buttons) }) return <SomeComponent /> }
Checks if element support this event type
import useEventListener from 'use-typed-event-listener' export default (props: Props) => { // this pass as HTMLElement supports copy event useEventListener(document.body, 'copy', (event) => { console.log(event.clipboardData) }) // as Window doesn't support copy event useEventListener(window, 'copy', (event) => { // this throws `Property 'clipboardData' does not exist on type 'Event'.ts(2339)` console.log(event.clipboardData) }) return <SomeComponent /> }