Search code examples
javascriptcssreactjsmaterial-uiappbar

Collapse one AppBar and show another AppBar at the same time on scroll in Material UI


I have Header.js component. Inside it, I have two AppBar, first AppBar is sticky, and the second is not. By default, only second AppBar showed. When we scroll, I want the second AppBar to collapse and the first AppBar to show stickied in the top of the screen.

I have seen useScrollTrigger() from Material-ui documentation here, but it only show to hide AppBar on scroll.

// Header.js
import React from "react";
import { AppBar, Toolbar, Typography } from "@material-ui/core";

export default function Header() {
  return (
    <>
    <AppBar position="static">
      <Toolbar>
        <Typography variant="h6">First AppBar</Typography>
      </Toolbar>
    </AppBar>
    <AppBar position="static">
      <Toolbar>
        <Typography variant="h6">Second AppBar</Typography>
      </Toolbar>
    </AppBar>
    </>
  );
}

Here is my sandbox link


Solution

  • This code seems run like you want. I used material-ui demo

    import React from "react";
    import { AppBar, Toolbar, Typography } from "@material-ui/core";
    import useScrollTrigger from '@material-ui/core/useScrollTrigger';
    import Slide from '@material-ui/core/Slide';
    
    function HideOnScroll(props) {
      const { children, window } = props;
      const trigger = useScrollTrigger({ target: window ? window() : undefined });
    
      return (
        <Slide appear={false} direction="down" in={!trigger}>
          {children}
        </Slide>
      );
    }
    
    function ElevationScroll(props) {
      const { children, window } = props;
      const trigger = useScrollTrigger({
        disableHysteresis: true,
        threshold: 0,
        target: window ? window() : undefined,
      });
    
      return React.cloneElement(children, {
        elevation: trigger ? 4 : 0,
      });
    }
    
    
    export default function Header(props) {
      return (
        <>
          <ElevationScroll  {...props}>
          <AppBar>
            <Toolbar>
              <Typography variant="h6">First AppBar</Typography>
            </Toolbar>
          </AppBar>
          </ElevationScroll >
          {/* second appbar */}
          <HideOnScroll {...props}>
          <AppBar>
            <Toolbar>
              <Typography variant="h6">Second AppBar</Typography>
            </Toolbar>
          </AppBar>
          </HideOnScroll>
        </>
      );
    }