2023-02-13 15:22:47 -06:00
|
|
|
import React, { useRef, useEffect, ReactNode, RefObject } from "react";
|
|
|
|
|
|
|
|
interface Props {
|
|
|
|
children: ReactNode;
|
|
|
|
onClickOutside: Function;
|
2023-02-18 21:32:02 -06:00
|
|
|
className?: string;
|
2023-02-13 15:22:47 -06:00
|
|
|
}
|
|
|
|
|
|
|
|
function useOutsideAlerter(
|
|
|
|
ref: RefObject<HTMLElement>,
|
|
|
|
onClickOutside: Function
|
|
|
|
) {
|
|
|
|
useEffect(() => {
|
|
|
|
function handleClickOutside(event: Event) {
|
|
|
|
if (
|
|
|
|
ref.current &&
|
|
|
|
!ref.current.contains(event.target as HTMLInputElement)
|
|
|
|
) {
|
|
|
|
onClickOutside();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
// Bind the event listener
|
|
|
|
document.addEventListener("mousedown", handleClickOutside);
|
|
|
|
return () => {
|
|
|
|
// Unbind the event listener on clean up
|
|
|
|
document.removeEventListener("mousedown", handleClickOutside);
|
|
|
|
};
|
|
|
|
}, [ref, onClickOutside]);
|
|
|
|
}
|
|
|
|
|
2023-02-18 21:32:02 -06:00
|
|
|
export default function OutsideAlerter({
|
|
|
|
children,
|
|
|
|
onClickOutside,
|
|
|
|
className,
|
|
|
|
}: Props) {
|
2023-02-13 15:22:47 -06:00
|
|
|
const wrapperRef = useRef(null);
|
|
|
|
useOutsideAlerter(wrapperRef, onClickOutside);
|
|
|
|
|
2023-02-18 21:32:02 -06:00
|
|
|
return (
|
|
|
|
<div ref={wrapperRef} className={className}>
|
|
|
|
{children}
|
|
|
|
</div>
|
|
|
|
);
|
2023-02-13 15:22:47 -06:00
|
|
|
}
|