简体   繁体   中英

MUI ScrollToTop component with the useScrollTrigger hook is not working

I'm creating a ScrollToTop component by using MUI useScrollTrigger hook https://mui.com/material-ui/react-app-bar/#usescrolltrigger-options-trigger

Here is the sample code: https://codesandbox.io/s/stackoverlow-mui-usescrolltrigger-er9z4y

Problems

  1. The ScrollTop component doesn't appear after scrolling some pixels even after scrolling to the bottom of the page.

Here is the screenshot. The ScrollToTop component should appear around the area I marked.
As we could see that the trigger value from the useScrollTrigger hook returns a false value. It should return a true value if we scrolled the page. 在此处输入图像描述

  1. If we uncomment the ScrollToTop component, the ScrollToTop component would appear. Then if we click the ScrollToTop component, the screen would not go to the top of the page.

Here is the screenshot. 在此处输入图像描述

Step To Reproduce

For problem 1:

  1. Open the demo (codesandbox link) above.
  2. Scroll to the bottom of the page.

For problem 2:

  1. Open the demo (codesandbox link) above.
  2. Comment only the ScrollToTop component.
  3. Scroll to the bottom of the page.
  4. Click the ScrollToTop component.

Expected conditions

  1. For problem 1: the ScrollTop component appears after scrolling some pixels.
  2. For problem 2: the ScrollTop component should bring the screen to the top of the page after being clicked.

Problem here is useScrollTrigger use the by default window as target. But in your example your main content box is having the scroll. So you need to pass the reference of this main content box as target to the useScrollTrigger.

Refer - https://stackoverflow.com/a/56743659/1133582

Something as below -

const [scrollTarget, setScrollTarget] = React.useState<Node | undefined>(undefined);    

<Box ref={(node: Node) => {
          if (node) {
            setScrollTarget(node);
          }
        }} className={classes.pageOverflow}>
      <Toolbar id="back-to-top-anchor" className={classes.toolbar} />

      <Box className={classes.longBox}>Top Of the page</Box>

      <ScrollToTop scrollTarget={scrollTarget}>
        <Fab size="small" color="secondary" className={classes.scrollToTop}>
          <IconKeyboardDoubleArrowUpRounded />
        </Fab>
      </ScrollToTop>
    </Box>

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