Switch between two AppBars simultaneously while scrolling in Material UI

In my Header.js component, I have two AppBars. The first one is sticky and the second one is not initially visible. As we scroll down, I want the second AppBar to collapse and the first one to stay stickied at the top of the screen.

I looked at the Material-UI documentation and found the useScrollTrigger() method, but it only provides guidance on hiding an 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>
    </>
  );
}

You can view my sandbox example here.

Answer №1

I utilized the material-ui demo to ensure that this code functions as intended and it seems to be working correctly.

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>
    </>
  );
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Limiting ng-repeat in AngularJS when the last item on the object is reached

I have a large object being repeated using ng-repeat, and it runs smoothly on Chrome and Opera. However, when it comes to browsers like Mozilla and IE, the performance is very slow. I tried implementing pagination, which helped speed things up, but ideally ...

The jQuery ajax function functions flawlessly on a local environment, but encounters issues when used on a

After spending the entire day researching this issue, it appears to be a common problem without a solution in sight. The challenge I am facing involves using jquery's $.ajax() function to update database values through a service call. While it works ...

Having Issues with Material-UI Lists Rendering?

I am having an issue with rendering a list of posts on the index page. I can successfully create posts by clicking the 'Add Post' button and submitting the form on the /posts/new route. However, the list of posts is not showing up on the index pa ...

Tips for updating the content of a div with fresh data using a slideshow effect in jQuery

Imagine you have a div called A and an array filled with text data. When t=0, div A will display $data[0]. Then, after every n seconds, I want the div to show the next piece of data in the array. I am interested in creating a transition effect similar to ...

What are the best ways to change the styling of jquery ui widgets?

Currently utilizing jQuery UI, I have encountered an issue with the font size within a dialog. When utilizing the standard settings, the font size appears to be excessively large. To address this, I used the element inspector to identify the class name o ...

unable to upload the image on firestorage

I am in the process of creating a social media website similar to Facebook or Instagram. While the email, password, and name authentication during signup worked smoothly, I encountered an issue with uploading the profile picture. I suspect that the problem ...

Is it best practice to use the AngularFirestoreCollection for updating Firestore items in AngularFire?

Within my application, I have a list that necessitates the use of an "or" condition. However, according to the documentation: "In this case, you should create a separate query for each OR condition and merge the query results in your app." Consequently ...

The issue with the ng-click property not triggering arises when it is assigned to a button that is generated dynamically

I need to construct a table dynamically based on the results returned from SQL. In this scenario, populating the table with the start time, end time, and user is straightforward: var StartTime = document.createElement('td'); var EndTime = docume ...

Steps for configuring mode as 'open' when generating a shadow element with vue-custom-element

Here is the method I used to generate a shadow component Vue.customElement('my-element', MyElement, { shadow: true, shadowCss: mystyles, }); ...

Is it possible to constantly retrieve data at one-second intervals in NextJS using getServerSideProps?

Is there a way to continuously fetch API data in NextJS using SSR (getServerSideProps) every second? This would involve the client making a request to the server every one second to receive the most up-to-date API data. Any suggestions? export const getS ...

What attribute should I utilize to ensure the image always takes priority over text when using @media queries?

resolution My goal is to have the image appear on top of the text when resizing the window, but maintain the appearance shown in the attached image when using a larger resolution. Below is the CSS code I am currently using: .section4 { text-align: cen ...

Using $nin alongside $and in Mongoose

Implementing a filter for an admin user using mongoose operations. The user should be able to view all saved files except for those that are classified as draft files. However, the admin user should still have access to their own saved draft files. Code ...

What is the optimal method for allowing users to modify the website name and various frontend settings in a ReactJS environment?

Developing a blog web application using nodejs, reactjs, and mongodb. Implementing a feature where admin users can customize their blog's name, color scheme, header image, sidebar image, and content without developer intervention. To start with, focus ...

Using Javascript to place a form inside a table

When attempting to add a Form inside a Table, only the input tags are being inserted without the form tag itself. $(function () { var table = document.getElementById("transport"); var row = table.insertRow(0); var cell1 = row.insertCell(0); ...

Utilizing GraphQL with React component's default props

When fetching records from a backend GraphQL service and attempting to render them with the Array.map function, I encounter an error because the records are undefined before they're loaded. I have already tried setting default props on the component b ...

Step-by-step guide to creating a dynamic button that not only changes its value but also

I am trying to implement a translation button on my website that changes its value along with the text. Currently, I have some code in place where the button toggles between divs, but I am struggling to make the button value switch as well. Given my limit ...

Creating a unique array of non-repeating numbers in ES6:

Looking to create an array of unique random numbers in ES6 without any repeats. Currently, my function is generating an array of random numbers that are repeating: winArray = [...Array(6)].map(() => Math.floor(Math.random() * 53)); Here is a non-ES6 ...

The error message "Cannot call expressjs listen on socket.ip" indicates that there

Currently working on a project involving websockets, but encountering an error in the code below: TypeError: require(...).listen is not a function Here's what I have tried so far: const app = require("express")(); const port = 3800; const ...

How to retrieve a random element from an array within a for loop using Angular 2

I'm in the process of developing a soundboard that will play a random sound each time a button is clicked. To achieve this, I have created an array within a for loop to extract the links to mp3 files (filename), and when a user clicks the button, the ...

Is it possible for me to include an ::after pseudo-element within a label that contains an input field?

I'm trying to create a clickable effect using CSS only with labels and inputs. However, I am struggling to replicate the same effect on my ::after pseudo-element without moving the input outside of the label. I attempted using flexbox order property b ...