Skip to content

Instantly share code, notes, and snippets.

@andrei-cacio
Created March 3, 2019 11:02
Show Gist options
  • Save andrei-cacio/ce8cf4dae5b94ad0d0ce5af08ab36cff to your computer and use it in GitHub Desktop.
Save andrei-cacio/ce8cf4dae5b94ad0d0ce5af08ab36cff to your computer and use it in GitHub Desktop.
ClickOutside
import React from 'react';
function ClickOutside({ children, onClick }) {
const refs = React.Children.map(children, () => React.createRef());
const handleClick = e => {
const isOutside = refs.every(ref => {
return !ref.current.contains(e.target);
});
if (isOutside) {
onClick();
}
};
return React.Children.map(children, (element, idx) =>
React.cloneElement(element, { ref: refs[idx] })
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment