Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fix the error "Property contains doesnt exist on type 'RefObject' using typescript and react?

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.

like image 716
saritha Avatar asked Oct 29 '25 14:10

saritha


1 Answers

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);
  }
};
like image 149
M KMD Avatar answered Nov 01 '25 08:11

M KMD



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!