0

i want to close the dialog on user clicking anywhere outside the dialog using typescript and react.

below is my code,

function Parent(){
    const [isDialogOpen, setIsDialogOpen] = React.useState(false);
    return (
        <Wrapper>
            <button onClick={() => setIsDialogOpen(true)}>click me </button>
            {isDialogOpen && 
                <Dialog
                    setIsDialogOpen={setIsDialogOpen}/>
            }
        </Wrapper> 
    );
}

function Dialog ({setIsDialogOpen, items}: Props) {
    return (
        <Wrapper>
            <Container_one>
                <span>title</span>
                <Description> some big description</Description>
            </Container_one>
            <Container_two>
                {items.map(item => (
                    <div
                        key={item.id}
                    />
                ))}
            </Container_two>
        </Wrapper>
    );

now how can i close the dialog meaning set the isDialogOpen state to false when user clicks anywhere outside the dialog using typescript and react.

could someone help me with this. thanks.

EDITstrong text

based on link provided i have tried below,

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>
    );

In doing so, i get error "Property contains doesnt exist on type 'RefObject'

how can i fix it. also how can remove eventlistener mousedown in unmount using useeffect.

could someone help me with this. thanks.

saritha
  • 619
  • 2
  • 12
  • 25

0 Answers0