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.
You should assert event.target as HTMLElement or HTMLDivElement.
By the way, You can set event argument as MouseEvent.
So, the right code is below:
const handleClickOutsideDialog = (event: MouseEvent) => {
if (
dialogRef &&
!dialogRef.contains(event.target as HTMLDivElement)
) {
alert('You clicked outside of me!');
setIsDialogOpen(false);
}
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With