i want to close the dialog on user clicking anywhere outside the dialog using typescript and react.
below is my code,
function Dialog ({setIsDialogOpen, items}: Props) {
const dialogRef = React.useRef<HTMLDivElement>(null);
React.useEffect(() => {
const handleClickOutsideDialog = (event: any) => {
if (
dialogRef &&
!dialogRef.contains(event.target)//error here
) {
alert('You clicked outside of me!');
setIsDialogOpen(false);
}
};
document.addEventListener('mousedown', handleClickOutsideDialog);
}, [setIsDialogOpen]);
return (
<Wrapper ref={dialogRef}>
<Container_one>
<span>title</span>
<Description> some big description</Description>
</Container_one>
<Container_two>
{items.map(item => (
<div
key={item.id}
/>
))}
</Container_two>
</Wrapper>
);
I am not sure what is wrong here. could someone help me with this. thanks.