Search code examples
reactjstypescriptmaterial-uipopover

React -- Material UI -- Popover, setAnchorEl(null) onClose of the popover does not set it to null for some reason


I have a Popover (imported from MaterialUI) inside of a MenuItem (also imported from MaterialUI). I have the open prop for the popover set to the boolean value of anchorEl. the onClose is what handles the anchorEl, and if I click outside of the popover it should set anchorEl to null. This is not the case, however. anchorEl never gets set to null once it has been given the value of the DOMelement, and I'm not sure what I'm doing wrong here.

Here are the parts of my code that are important for this question

    //state for the anchorEl (also handles the open/close for the popover)
    const [usernamePopoverAnchorEl, setUsernamePopoverAnchorEl] = React.useState<null | HTMLElement>(null);
    
    //handle popover open/close
    const handleUsernamePopoverClick = (e: any) => {
        setUsernamePopoverAnchorEl(e.currentTarget);
    }

    const usernamePopoverOpen = Boolean(usernamePopoverAnchorEl);

    const popoverHandleClose = () => {
        setUsernamePopoverAnchorEl(null);
        console.log(usernamePopoverAnchorEl);
    }
    
    //menuItems with the popovers that don't close
    <MenuItem onClick={handleUsernamePopoverClick}>
        <span>
            <p>Change username</p>
        </span>
        <Popover open={usernamePopoverOpen} anchorEl={usernamePopoverAnchorEl} onClose={popoverHandleClose}>
            <p>Testing helloooo!</p>
        </Popover>
    </MenuItem>

The value of anchorEl remains the HTML element (the anchor for the popover) even though I have setAnchorEl(null) in the handleClose. Here is a picture of the logs in the console for anchorEl when I click outside of the popover. console.logs of anchorEl

I have basically copied this from the documentation (other than the menuItem), so I have no idea why the popover won't close...


Solution

  • try adding event.stopPropagation() worked for me.

    const popoverHandleClose = (event) => {
                event.stopPropagation();
                setUsernamePopoverAnchorEl(null);
                console.log(usernamePopoverAnchorEl);
            }