handleclickoutside custom hook react

Solutions on MaxInterview for handleclickoutside custom hook react by the best coders in the world

showing results for - "handleclickoutside custom hook react"
Federico
01 May 2016
1import { useState, useEffect, useRef } from 'react';
2
3export default function useComponentVisible(initialIsVisible) {
4    const [isComponentVisible, setIsComponentVisible] = useState(initialIsVisible);
5    const ref = useRef<HTMLDivElement>(null);
6
7    const handleHideDropdown = (event: KeyboardEvent) => {
8        if (event.key === 'Escape') {
9            setIsComponentVisible(false);
10        }
11    };
12
13    const handleClickOutside = (event: Event) => {
14        if (ref.current && !ref.current.contains(event.target as Node)) {
15            setIsComponentVisible(false);
16        }
17    };
18
19    useEffect(() => {
20        document.addEventListener('keydown', handleHideDropdown, true);
21        document.addEventListener('click', handleClickOutside, true);
22        return () => {
23            document.removeEventListener('keydown', handleHideDropdown, true);
24            document.removeEventListener('click', handleClickOutside, true);
25        };
26    });
27
28    return { ref, isComponentVisible, setIsComponentVisible };
29}
30