Skip to content

Instantly share code, notes, and snippets.

@vilindberg
Created February 6, 2019 20:54
Show Gist options
  • Save vilindberg/50d9b4fe6d89efa32f116679dce31e2e to your computer and use it in GitHub Desktop.
Save vilindberg/50d9b4fe6d89efa32f116679dce31e2e to your computer and use it in GitHub Desktop.
import { useRef, useCallback, useEffect } from "react";
export const useClickOutside = (callback, active) => {
const ref = useRef(null);
const handler = useCallback(
e => {
if (ref.current && !ref.current.contains(e.target)) {
callback();
}
},
[callback],
);
useEffect(
() => {
if (active) {
window.addEventListener("click", handler);
return () => {
window.removeEventListener("click", handler);
};
}
},
[handler, active],
);
return ref;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment