From d27880ff134b04cfd7abcc3eaf1ee82619a283de Mon Sep 17 00:00:00 2001 From: Julien Date: Fri, 30 Sep 2022 15:32:37 +0200 Subject: [PATCH] feat: add media query support (#194 from @modex98) --- src/useEventListener/useEventListener.ts | 32 ++++++++++++++++-------- 1 file changed, 22 insertions(+), 10 deletions(-) diff --git a/src/useEventListener/useEventListener.ts b/src/useEventListener/useEventListener.ts index 607ba260..2655e2c9 100644 --- a/src/useEventListener/useEventListener.ts +++ b/src/useEventListener/useEventListener.ts @@ -2,6 +2,14 @@ import { RefObject, useEffect, useRef } from 'react' import { useIsomorphicLayoutEffect } from '..' +// MediaQueryList Event based useEventListener interface +function useEventListener( + eventName: K, + handler: (event: MediaQueryListEventMap[K]) => void, + element: RefObject, + options?: boolean | AddEventListenerOptions, +): void + // Window Event based useEventListener interface function useEventListener( eventName: K, @@ -32,11 +40,16 @@ function useEventListener( function useEventListener< KW extends keyof WindowEventMap, KH extends keyof HTMLElementEventMap, - T extends HTMLElement | void = void, + KM extends keyof MediaQueryListEventMap, + T extends HTMLElement | MediaQueryList | void = void, >( - eventName: KW | KH, + eventName: KW | KH | KM, handler: ( - event: WindowEventMap[KW] | HTMLElementEventMap[KH] | Event, + event: + | WindowEventMap[KW] + | HTMLElementEventMap[KH] + | MediaQueryListEventMap[KM] + | Event, ) => void, element?: RefObject, options?: boolean | AddEventListenerOptions, @@ -50,19 +63,18 @@ function useEventListener< useEffect(() => { // Define the listening target - const targetElement: T | Window = element?.current || window - if (!(targetElement && targetElement.addEventListener)) { - return - } + const targetElement: T | Window = element?.current ?? window + + if (!(targetElement && targetElement.addEventListener)) return // Create event listener that calls handler function stored in ref - const eventListener: typeof handler = event => savedHandler.current(event) + const listener: typeof handler = event => savedHandler.current(event) - targetElement.addEventListener(eventName, eventListener, options) + targetElement.addEventListener(eventName, listener, options) // Remove event listener on cleanup return () => { - targetElement.removeEventListener(eventName, eventListener) + targetElement.removeEventListener(eventName, listener) } }, [eventName, element, options]) }