Function useClickOutside

  • Allows you to listen a clicks outside a specified element and execute a callback.

    Parameters

    • callback: ((e: PointerEvent | MouseEvent) => void)

      A function to execute when the user click's outside the specified element. As a parameter it takes an event which is either a MouseEvent or PointerEvent depending on the eventType specified. The e.target property will contain the element that was clicked.

        • (e): void
        • Parameters

          • e: PointerEvent | MouseEvent

          Returns void

    • options: ClickOutsideOptions = {}

      Allows configuring how the hook works.

    Returns MutableRefObject<null>

    A reference you need to attach to the element to target. Can be used as a normal ref as well.

    const DemoUseClickOutside = () => {
    const ref = useClickOutside(e => (e.target as HTMLElement).style.backgroundColor = "black");
    return (
    <div style={{padding: '50px', backgroundColor: 'red'}}>
    <div ref={ref} style={{padding: '50px', backgroundColor: 'blue'}}>
    <div style={{padding: '50px', backgroundColor: 'yellow'}}>
    :)
    </div>
    </div>
    </div>
    );
    };