Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions lib/src/hooks/useBodyScrollLock.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import { useLayoutEffect } from "react";

const useLockBodyScroll = (value: boolean): void => {
useLayoutEffect((): (() => void) => {
value
? (document.body.style.overflow = "hidden")
: (document.body.style.overflow = "auto");

return () => (document.body.style.overflow = "auto");
}, []);
};

export { useLockBodyScroll };
33 changes: 33 additions & 0 deletions lib/src/hooks/useClickOutside.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import { RefObject, useEffect } from "react";

type AnyEvent = MouseEvent | TouchEvent;

function useClickOutside<T extends HTMLElement = HTMLElement>(
ref: RefObject<T>,
handler: (event: AnyEvent) => void
): void {
useEffect(() => {
const listener = (event: AnyEvent) => {
const el = ref?.current;

// Do nothing if clicking ref's element or descendent elements
if (!el || el.contains(event.target as Node)) {
return;
}

handler(event);
};

document.addEventListener(`mousedown`, listener);
document.addEventListener(`touchstart`, listener);

return () => {
document.removeEventListener(`mousedown`, listener);
document.removeEventListener(`touchstart`, listener);
};

// Reload only if ref or handler changes
}, [ref, handler]);
}

export { useClickOutside };