0

React v.18.3.1

react-native v.0.74.1

Materal-UI v.5.15.3

DEMO: CodeSandBox Demo

I have a popover which is triggered by an icon button. and closes in the following two scenarios:

  • When the user clicks somewhere in the screen
  • When the user scroll more than 50 px in any y-direction (up or down)
const [popoverAnchor, setPopoverAnchor] = useState(null);
const [popoverInfo, setPopoverInfo] = useState(null); 
const [initialScrollPosition, setInitialScrollPosition] = useState(null);

//On Questionmark Button Click
const openPopover = (event, infoText) => {
    setInitialScrollPosition(window.scrollY); 
    setPopoverAnchor(event.currentTarget);
    setPopoverInfo(popoverInfo => popoverInfo && popoverInfo.text === infoText ? null : { anchor: popoverAnchor, text: infoText });
};

//Popover OnClose Event Listener Triggers this function
const closePopover = () => {
    setPopoverInfo(null);
    setPopoverAnchor(null);
};

useEffect(() => {
    const handleScroll = () => {
        if (initialScrollPosition !== null && Math.abs(window.scrollY - initialScrollPosition) > 50) {
            closePopover();
            setInitialScrollPosition(null);
        }
    };

    window.addEventListener('scroll', handleScroll);
    return () => {
        window.removeEventListener('scroll', handleScroll);
    };
}, [initialScrollPosition]);

<IconButton onClick={(e) => openPopover(e, item.infoText)} size="small">
      <HelpOutlineIcon />
</IconButton>

<Popover
      open={Boolean(popoverAnchor)}
      anchorEl={popoverAnchor}
      onClose={closePopover}
      anchorOrigin={{
            vertical: 'bottom',
            horizontal: 'left',
      }}
      transformOrigin={{
            vertical: 'top',
            horizontal: 'left'
      }}
      >
      text
</Popover>

The above code is working great however when the popover is triggered is adding padding-right:17px and overflow:hidden on the <body> tag for some reason. To address this issue i have added disableScrollLock on the popover which solves the issue (Related GitHub Issue: 19961)

<Popover disableScrollLock ...></Popover>

With the above solution the scenario "When the user clicks somewhere in the screen" is still working but the disableScrollLock is causing issues on "When the user scroll more than 50 px in any y-direction (up or down)"


THE ISSUE: When the popover is open and the user is scrolling the popover is moving to the bottom-left corner of the screen and then disappears instead of disappearing on current anchor location.(similar github issue 8567) and youtube video demo

I'm not exactly sure why this is happening and I'm fairly new to React, but the require solution i want should have the following:

  • Popover should close on spot, when the user clicks somewhere in the screen
  • Popover should close on spot, when the user scroll more than 50 px in any y-direction
  • Popover should open without adding additional CSS to the tag

0