Detect click outside React component using hooks

后端 未结 2 875
醉梦人生
醉梦人生 2021-01-02 11:33

I am finding that I am reusing behaviour across an app that when a user clicks outside an element I can hide it.

With the introduction of hooks is this something I

2条回答
  •  醉酒成梦
    2021-01-02 12:15

    This is possible.

    You can create a reusable hook called useComponentVisible

    import { useState, useEffect, useRef } from 'react';
    
    export default function useComponentVisible(initialIsVisible) {
        const [isComponentVisible, setIsComponentVisible] = useState(initialIsVisible);
        const ref = useRef(null);
    
        const handleHideDropdown = (event: KeyboardEvent) => {
            if (event.key === 'Escape') {
                setIsComponentVisible(false);
            }
        };
    
        const handleClickOutside = (event: Event) => {
            if (ref.current && !ref.current.contains(event.target as Node)) {
                setIsComponentVisible(false);
            }
        };
    
        useEffect(() => {
            document.addEventListener('keydown', handleHideDropdown, true);
            document.addEventListener('click', handleClickOutside, true);
            return () => {
                document.removeEventListener('keydown', handleHideDropdown, true);
                document.removeEventListener('click', handleClickOutside, true);
            };
        });
    
        return { ref, isComponentVisible, setIsComponentVisible };
    }
    

    Then in the component you wish to add the functionality to do the following:

    const DropDown = () => {
    
        const { ref, isComponentVisible } = useComponentVisible(true);
    
        return (
           
    {isComponentVisible && (

    Going into Hiding

    )}
    ); }

    Find a codesandbox example here.

提交回复
热议问题