2023-02-13 15:22:47 -06:00
|
|
|
import React, { useRef, useEffect, ReactNode, RefObject } from "react";
|
|
|
|
|
2023-03-22 18:11:54 -05:00
|
|
|
type Props = {
|
2023-02-13 15:22:47 -06:00
|
|
|
children: ReactNode;
|
|
|
|
onClickOutside: Function;
|
2023-02-18 21:32:02 -06:00
|
|
|
className?: string;
|
2023-03-22 18:11:54 -05:00
|
|
|
};
|
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)
|
|
|
|
) {
|
2023-03-23 10:25:17 -05:00
|
|
|
onClickOutside(event);
|
2023-02-13 15:22:47 -06:00
|
|
|
}
|
|
|
|
}
|
2023-05-22 07:20:48 -05:00
|
|
|
document.addEventListener("mousedown", handleClickOutside);
|
2023-02-13 15:22:47 -06:00
|
|
|
return () => {
|
2023-05-22 07:20:48 -05:00
|
|
|
document.removeEventListener("mousedown", handleClickOutside);
|
2023-02-13 15:22:47 -06:00
|
|
|
};
|
|
|
|
}, [ref, onClickOutside]);
|
|
|
|
}
|
|
|
|
|
2023-02-24 11:32:28 -06:00
|
|
|
export default function ({ 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
|
|
|
}
|