diff --git a/.changeset/wild-socks-type.md b/.changeset/wild-socks-type.md new file mode 100644 index 0000000..118b89e --- /dev/null +++ b/.changeset/wild-socks-type.md @@ -0,0 +1,5 @@ +--- +'@raddix/use-event-listener': minor +--- + +Add null type in first parameter of useEventListener diff --git a/packages/hooks/use-event-listener/src/index.ts b/packages/hooks/use-event-listener/src/index.ts index 037d55f..3ca78f8 100644 --- a/packages/hooks/use-event-listener/src/index.ts +++ b/packages/hooks/use-event-listener/src/index.ts @@ -1,11 +1,10 @@ import { type RefObject, useEffect, useRef } from 'react'; -export const _window = typeof window !== 'undefined' ? window : global.window; -export const _document = - typeof document !== 'undefined' ? document : global.document; +export const _window = typeof window !== 'undefined' ? window : null; +export const _document = typeof document !== 'undefined' ? document : null; export const useEventListener = ( - target: RefObject | EventTarget, + target: RefObject | EventTarget | null, eventType: T, callback: (event: HTMLElementEventMap[T]) => void, options?: boolean | AddEventListenerOptions @@ -17,6 +16,7 @@ export const useEventListener = ( }, [callback]); useEffect(() => { + if (target === null) return; const targetElement = 'current' in target ? target.current : target; if (!targetElement?.addEventListener) return;