Creating A Scroll To Top Button With React MUI

React

29/12/2022


There's a decent article by Henrik from Apollo Learn on how to create a Scroll To Top button. However, it contains a bug 🐛: namely, it uses the body tag instead of window as a target for scrolling.

The problem is that document will be undefined when useScrollTrigger is first run.

ScrollToTopFab.tsx
TSX
function ScrollToTopFab() {
// Use `window` instead of `body` as `document` will be `undefined` when the
// hooks first runs. By default, useScrollTrigger will attach itself to `window`.
const trigger = useScrollTrigger({
// Number of pixels needed to scroll to toggle `trigger` to `true`.
threshold: 100,
})
const scrollToTop = useCallback(() => {
window.scrollTo({ top: 0, behavior: "smooth" })
}, [])
return (
<Zoom in={trigger}>
<Box
role="presentation"
// Place the button in the bottom right corner.
sx={{
position: "fixed",
bottom: 32,
right: 32,
zIndex: 1,
}}
>
<Fab
onClick={scrollToTop}
color="primary"
size="small"
aria-label="Scroll back to top"
>
<KeyboardArrowUp fontSize="medium" />
</Fab>
</Box>
</Zoom>
)
}
export default ScrollToTopFab

The variable trigger is a boolean responsible for showing the button once the user has scrolled enough. If the user clicks on the button, scrollToTop will trigger a smooth scroll to the top of the window.


WRITTEN BY

Code and stuff