UNPKG

1.39 kBPlain TextView Raw
1/*
2 * Copyright 2021 Adobe. All rights reserved.
3 * This file is licensed to you under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License. You may obtain a copy
5 * of the License at http://www.apache.org/licenses/LICENSE-2.0
6 *
7 * Unless required by applicable law or agreed to in writing, software distributed under
8 * the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
9 * OF ANY KIND, either express or implied. See the License for the specific language
10 * governing permissions and limitations under the License.
11 */
12
13import {RefObject, useEffect, useRef} from 'react';
14
15export function useEvent<K extends keyof GlobalEventHandlersEventMap>(
16 ref: RefObject<EventTarget>,
17 event: K,
18 handler: (this: Document, ev: GlobalEventHandlersEventMap[K]) => any,
19 options?: boolean | AddEventListenerOptions
20) {
21 let handlerRef = useRef(handler);
22 handlerRef.current = handler;
23
24 let isDisabled = handler == null;
25
26 useEffect(() => {
27 if (isDisabled) {
28 return;
29 }
30
31 let element = ref.current;
32 let handler = (e: GlobalEventHandlersEventMap[K]) => handlerRef.current.call(this, e);
33
34 element.addEventListener(event, handler, options);
35 return () => {
36 element.removeEventListener(event, handler, options);
37 };
38 }, [ref, event, options, isDisabled]);
39}