The ScrollToTop feature in MUI component seems to be malfunctioning when paired with the useScrollTrigger hook

I am in the process of developing a custom ScrollToTop component using MUI's useScrollTrigger hook. More information can be found at this link

Feel free to check out the sample code here: https://codesandbox.io/s/stackoverlow-mui-usescrolltrigger-er9z4y

Challenges

  1. The ScrollTop component does not show up after scrolling, even when reaching the bottom of the page.

Please refer to the screenshot below. The ScrollToTop component should appear in the area I have marked.
When analyzing the code, it appears that the trigger value from the useScrollTrigger hook is consistently returning a value of false, instead of changing to true upon scrolling. https://i.sstatic.net/22YLg.png

  1. If we were to remove the comment tags from the ScrollToTop component, it would become visible. However, clicking on the component does not return the screen to the top of the page as expected.

Refer to the screenshot below. https://i.sstatic.net/ip94x.png

Steps To Reproduce

For the first problem:

  1. Access the demo using the codesandbox link provided above.
  2. Scroll down to the bottom of the page.

Regarding the second issue:

  1. Also access the demo using the codesandbox link provided above.
  2. Uncomment the ScrollToTop component.
  3. Scroll down to the bottom of the page.
  4. Click on the ScrollToTop component.

Expected Results

  1. For the first problem: The ScrollTop component should become visible after scrolling a certain distance.
  2. Concerning the second challenge: Clicking on the ScrollTop component should return the screen to the top of the page.

Answer №1

Issue arises when useScrollTrigger defaults to using the window as the target. However, in your scenario, the main content box is the one with the scroll. Therefore, you must specify the reference of this main content box as the target for useScrollTrigger.

Reference -

It should look something like this -

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>

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

Difficulty in making Materialize.css column match the height of the entire row

Utilizing React.js, Materialize.css, and certain MaterialUI components in collaboration to build a website. Developed a header (React component, basic div with title and logout button) for the site using a Materialize.css "grid". Issue: The react compone ...

Retrieving specific data from nested arrays in Vue.js

I am currently working on Vue.js template development and facing an issue with filtering nested data in a faq section. When I try to add a search bar, the nested data array returns all data without proper filtering. Dom <v-container> <v ...

In AngularJS, showcasing five elements at a time from an array containing 'n' items before looping back to the beginning

I'm a beginner in AngularJS and facing a scenario where I need to display 5 items from an array containing multiple items. The requirement is to initially show items 1-5 and then, after 2-3 seconds, add a 6th item at the top and remove the last item f ...

What is the best way to temporarily bold a cell item within a table row for a specified duration of time?

I am experiencing an issue with a section of my code where I am fetching values from the server and updating a table if a certain value is not present. Once the update is made, I want to visually notify the user by temporarily making the cell's value ...

How can you efficiently manage Access & Refresh tokens from various Providers?

Imagine I am allowing my users to connect to various social media platforms like Facebook, Instagram, Pinterest, and Twitter in order to use their APIs. As a result, I obtain access tokens for each of these providers. Based on my research, it seems advisa ...

Create SCSS to style multiple CSS classes

Are there more efficient ways to create css helper classes like the ones shown below? Can I use scss to generate cleaner and better classes? Thank you. .m-1 { margin: 1px !important; } .m-2 { margin: 2px !important } .m-3 { margin: 3px !important } .m-4 ...

What is the best way to attach an event listener to a React component?

Currently, I am in the process of developing a React web application (version 16.13.0) and I am looking to incorporate a flash message component that will display the status after a form submission. If there is an existing standard solution available, that ...

How to display (fade in a portion of an image) using .SVG

I have the following code in my DOM: <div class="icon-animated"><img src="icon_non_active.svg" id="icon_non_active"></div> There are two icons (.svg) available: icon_non_active & icon_active Can I animate the transformation from i ...

Is there a way to conceal an element using identical markup with jquery?

Having trouble with two custom dropdown lists that share the same markup. Ideally, only one should be visible at a time. However, both are currently opening simultaneously. Additionally, I need them to close when clicking outside of the list. It's ne ...

Looping through elements with jQuery's `each` method within another `

When using div containers in my code, I wanted to loop over them and then iterate through the items within each container. Instead of $('.stackContainer .stackItem').each(, I was looking for a solution like this: // setup stacks $('.stackC ...

Retrieve the input field value using JavaScript within a PHP iteration loop

I've implemented an input box inside a while loop to display items from the database as IDs like 001,002,003,004,005 and so on. Each input box is accompanied by a button beneath it. My Desired Outcome 1) Upon clicking a button, I expect JavaScript t ...

Maintaining awareness of which accordion drawer is currently open within a React application

Just getting started with coding, I recently created a collapsible accordion in a NextJs app using the react-collapse package. Everything seems to be working fine, but I'm running into an issue with keeping track of which 'drawer' is current ...

Adjusting Spacing Between Characters

I've been looking for a way to convert regular characters (ABC) to full-width characters (ABC), but I haven't had any luck so far. That's why I'm turning to you guys for help. Currently, I don't have any JavaScript code writt ...

The response data from Axios cannot be stored using useState hook

Struggling with fetching data from my express backend and MySQL database to display on my react frontend using axios. However, I'm facing issues when trying to update the fetched data using the useState hook. Here is how my frontend function is struc ...

How come my image is not aligned to the right of the header in my HTML code?

My attempt to align an image to the right side of my heading using code was unsuccessful. Here is the HTML snippet I used: /* Aligning with CSS */ #colorlib-logo img { display: flex; align-items: center; width: 30px; height: 30px; } #colorli ...

Creating three functions with the same name, one with a callback, another with a promise, and the third with async/await, can

I am looking to create a versatile function that can be used in 3 different ways to handle npm dependencies Using Promises Using callbacks Using async/await For Instance 1) Using async/await var mongoose = require('mongoose'); async fu ...

What is the best way to check if a user input matches any of the items saved in an array?

I'm working on coding a hangman app and I have a question. How can I compare the user input "userGuess" to the array "array" that consists of letters split from the randomly selected word "word"? If the "userGuess" matches any of the values in the "a ...

What are some strategies for maximizing the value of the initial click?

For the past few days, I've been struggling with this particular aspect of the project. Despite extensive research, I haven't been able to find a solution. The issue lies in retrieving a variable from the contextAPI. Although it updates to the co ...

Choosing specific child elements based on their css attribute valuesUnique: "Targeting

I am attempting to customize the appearance of any child divs with the class 'header' that are within parent divs with a class of 'recipes'. I understand that I could simply target .category-recipes .header, but the parent div may vary ...

"Vue3 offers the ability to return a multi-layer object through the Provide-Inject

While implementing provide-inject in my personal project, I encountered an issue where the value returned by inject() was a RefImpl Object. This meant that I had to access the actual value using inject().value.value instead of just inject().value. Here is ...