简体   繁体   中英

How to remove event listener mousedown on component unmount using useeffect react hook?

i want to remove eventlistener mousedown on component unmount using react usehook 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>
);

this works fine. but i want to remove event listener on unmount using usehook. how can i do it. could someone help me with this. thanks.

You add the removeEventListener() in the cleanup func.

You can find the information in the documentation .

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

    return () => { 
        document.removeEventListener('mousedown', handleClickOutsideDialog);
    }
}, [setIsDialogOpen]);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM