Files
headlessui/packages/@headlessui-react/src/hooks/use-window-event.ts
T
Robin Malfait c219d87a69 Use ownerDocument instead of document (#1158)
* use `ownerDocument` instead of `document`

This should ensure that in iframes and new windows the correct document
is being used.

* update changelog
2022-03-10 13:37:50 +01:00

21 lines
572 B
TypeScript

import { useEffect } from 'react'
import { useLatestValue } from './use-latest-value'
export function useWindowEvent<TType extends keyof WindowEventMap>(
type: TType,
listener: (ev: WindowEventMap[TType]) => any,
options?: boolean | AddEventListenerOptions
) {
let listenerRef = useLatestValue(listener)
useEffect(() => {
function handler(event: WindowEventMap[TType]) {
listenerRef.current(event)
}
window.addEventListener(type, handler, options)
return () => window.removeEventListener(type, handler, options)
}, [type, options])
}