All files / src/events use-dom-event.ts

100% Statements 10/10
100% Branches 4/4
100% Functions 4/4
100% Lines 9/9

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 4935x   35x           358x   435x                                               35x           274x 133x   133x 132x        
import { useEffect, RefObject } from "react"
 
export function addDomEvent(
    target: EventTarget,
    eventName: string,
    handler: EventListener,
    options?: AddEventListenerOptions
) {
    target.addEventListener(eventName, handler, options)
 
    return () => target.removeEventListener(eventName, handler, options)
}
 
/**
 * Attaches an event listener directly to the provided DOM element.
 *
 * Bypassing React's event system can be desirable, for instance when attaching non-passive
 * event handlers.
 *
 * ```jsx
 * const ref = useRef(null)
 *
 * useDomEvent(ref, 'wheel', onWheel, { passive: false })
 *
 * return <div ref={ref} />
 * ```
 *
 * @param ref - React.RefObject that's been provided to the element you want to bind the listener to.
 * @param eventName - Name of the event you want listen for.
 * @param handler - Function to fire when receiving the event.
 * @param options - Options to pass to `Event.addEventListener`.
 *
 * @public
 */
export function useDomEvent(
    ref: RefObject<EventTarget>,
    eventName: string,
    handler?: EventListener | undefined,
    options?: AddEventListenerOptions
) {
    useEffect(() => {
        const element = ref.current
 
        if (handler && element) {
            return addDomEvent(element, eventName, handler, options)
        }
    }, [ref, eventName, handler, options])
}