Skip to content

Instantly share code, notes, and snippets.

@andrei-cacio
Last active March 28, 2019 17:43
Show Gist options
  • Select an option

  • Save andrei-cacio/c54173c36a422f194a808628a0e38430 to your computer and use it in GitHub Desktop.

Select an option

Save andrei-cacio/c54173c36a422f194a808628a0e38430 to your computer and use it in GitHub Desktop.

Revisions

  1. andrei-cacio revised this gist Mar 19, 2019. 1 changed file with 1 addition and 1 deletion.
    2 changes: 1 addition & 1 deletion click-outide.jsx
    Original file line number Diff line number Diff line change
    @@ -17,7 +17,7 @@ function ClickOutsideH({ children, onClick }) {
    return function() {
    document.removeEventListener("click", handleClick);
    };
    });
    }, []);

    return React.Children.map(children, (element, idx) =>
    React.cloneElement(element, { ref: refs[idx] })
  2. andrei-cacio created this gist Mar 19, 2019.
    25 changes: 25 additions & 0 deletions click-outide.jsx
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,25 @@
    import React, { Component, useEffect, useCallback } from "react";

    function ClickOutsideH({ children, onClick }) {
    const refs = React.Children.map(children, () => React.createRef());
    const handleClick = useCallback(e => {
    const isOutside = refs.every(ref => {
    return !ref.current.contains(e.target);
    });
    if (isOutside) {
    onClick();
    }
    }, []);

    useEffect(() => {
    document.addEventListener("click", handleClick);

    return function() {
    document.removeEventListener("click", handleClick);
    };
    });

    return React.Children.map(children, (element, idx) =>
    React.cloneElement(element, { ref: refs[idx] })
    );
    }