Search code examples
cssreactjsfloating-action-button

How to move a FAB in react during scrolling


I want to have a Fab like this

<Box display="flex" alignItems="center"justifyContent="center">
     <Fab color="primary" aria-label="add" variant="extended" size="large" style={{position: 'absolute', bottom: '2.2rem'}}>
         <AddShoppingCartIcon />
         Add to shopping cart
     </Fab>
</Box>

When I enter the site, the button should be at the bottom with marginBottom: 0. When I scrole down till the end, the final position of the Fab should be e.g. marginBottom: 2rem. Does anyone know how to achieve this?

Thanks for your help


Solution

  • You can achieve this effect by using React hooks to update the style of the Fab component based on the user's scroll position. Here's an example implementation:

    import React, { useState, useEffect } from "react";
    import { Box, Fab } from "@material-ui/core";
    import AddShoppingCartIcon from "@material-ui/icons/AddShoppingCart";
    
    function ScrollableFab() {
      const [isScrolledToBottom, setIsScrolledToBottom] = useState(false);
    
      useEffect(() => {
        function handleScroll() {
          const scrolledToBottom =
            window.innerHeight + window.pageYOffset >= document.body.offsetHeight;
          setIsScrolledToBottom(scrolledToBottom);
        }
    
        window.addEventListener("scroll", handleScroll);
    
        return () => {
          window.removeEventListener("scroll", handleScroll);
        };
      }, []);
    
      const fabStyle = {
        position: "fixed",
        bottom: isScrolledToBottom ? "2.2rem" : "0",
      };
    
      return (
        <Box display="flex" alignItems="center" justifyContent="center">
          <Fab
            color="primary"
            aria-label="add"
            variant="extended"
            size="large"
            style={fabStyle}
          >
            <AddShoppingCartIcon />
            Add to shopping cart
          </Fab>
        </Box>
      );
    }
    
    export default ScrollableFab;