Is it possible to conceal my Sticky Div in MUI5 once I've scrolled to the bottom of the parent div?

Sample link to see the demonstration:

https://stackblitz.com/edit/react-5xt9r5?file=demo.tsx

I am looking for a way to conceal a fixed div once I reach the bottom of its parent container while scrolling down.

Below is a snippet illustrating how I structured the parent and fixed div elements:

    <Box
  sx={{
    width: 400,
    height: 300,
    overflow: 'auto',
    border: '1px solid #ccc',
    borderRadius: '4px',
  }}
>
  <ul>
    {Array.from({ length: 20 }, (_, index) => (
      <li key={index}>{`Text ${index + 1}`}</li>
    ))}
  </ul>
  <Box
    position="sticky"
    bottom={0}
    bgcolor="white"
    p={2}
    boxShadow={2}
    zIndex={100}
  >
    Hide this Div when parent div scrolled down
  </Box>
</Box>

I attempted to implement something using Material-UI's useScrollTrigger but I struggled to find an example where I could specify the target parent (which is what I actually needed).

https://mui.com/material-ui/react-app-bar/#back-to-top

Answer №1

Hey there! I wanted to share another solution with you that involves using the useScrollTrigger method.

export default function BoxSx() {
  const parentRef = React.useRef(null);
  const [node, setNode] = React.useState(undefined);
  
  // showSticky is set to true when the defined threshold is reached
  const showSticky = useScrollTrigger({
    target: node,
    threshold: 100
  });

  // As refs start as null, we use this useEffect hook to set the current node when the component loads
  React.useEffect(() => {
    setNode(parentRef.current);
  }, []);
  
  // This console.log will show whether the threshold was reached (true) or not (false)
  console.log(showSticky);

  return (
    <Box
      sx={{
        width: 400,
        height: 1000,
        overflow: 'auto',
        border: '1px solid #ccc',
        borderRadius: '4px',
      }}
      ref={parentRef}
    >
      <ul>
        {/* Generating a list of text items */}
        {Array.from({ length: 100 }, (_, index) => (
          <li key={index}>{`Text ${index + 1}`}</li>
        ))}
      </ul>
      <Box
        position="sticky"
        bottom={0}
        bgcolor="white"
        p={2}
        boxShadow={2}
        zIndex={100}
      >
        test
      </Box>
    </Box>
  );
}

I hope this solution proves to be useful for you.

Answer №2

    import * as React from 'react';
    import Box from '@mui/material/Box';

    export default function BoxSx() {
      const [hideSticky, setHideSticky] = React.useState(false);

      const handleScroll = (event) => {
        const target = event.target;
        if (target.scrollHeight - target.scrollTop === target.clientHeight) {
          setHideSticky(true);
        } else {
          setHideSticky(false);
        }
      };

      return (
        <Box
          sx={{
            width: 400,
            height: 300,
            overflow: 'auto',
            border: '1px solid #ccc',
            borderRadius: '4px',
          }}
          onScroll={handleScroll}
        >
          <ul>
            {Array.from({ length: 20 }, (_, index) => (
              <li key={index}>{`Text ${index + 1}`}</li>
            ))}
          </ul>
          {!hideSticky && (
            <Box
              position="sticky"
              bottom={0}
              bgcolor="white"
              p={2}
              boxShadow={2}
              zIndex={100}
            >
              Hide this Box when the parent div is scrolled down
            </Box>
          )}
        </Box>
      );
    }

provided a useful solution for the issue at hand.

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

What is the method for activating the on collapse event with a bootstrap navbar?

I am encountering a common issue with collapsing the navbar on smaller screens and triggering an event when the collapse button icon is clicked. Despite my efforts to find a solution, I have been unsuccessful in using the following JavaScript code: $(&apos ...

What is the best way to create a continuous loop of images on a never-ending

Many discussions cover similar topics, but I have not yet found a solution to my specific question. Currently, I am working on creating a model for a website and I am interested in incorporating an infinite rotating gallery with a limited number of images ...

Guide to transmitting and managing a JSON document utilizing JavaScript

When working on the server side, I receive a simple JSON file via REST that contains various IDs. Here is an example: [ { "_id": "5825a49dasdasdasd8417c1b6d5", } "_id": "dfsdfsdf4960932218417c1b6d5", } "_id": "23434344960932218417c1b6d5", },] To handle t ...

Exploring Text Color Verification with CSS in Selenium IDE

I am working on a project and want to ensure that my link is styled properly: <a class="title">My link</a> The CSS code used to style my link is as follows: a.title { color: #CC3333; } How can I confirm that the text "My link" is displayi ...

Tips for positioning a modal in the center specifically for zoomed-in mobile devices

I created a modal that uses the following function to center itself: center: function() { var top=Math.max($window.height() - $modal.outerHeight(),0) / 2; var left=Math.max($window.width() - $modal.outerWidth(),0) / 2; $modal.css({ ...

Is there a way to include an image in a serialized file?

What is the method to include image_form into form in Django? form - form.serialize() image_form - image $('#id_submit').click(function(e) { e.preventDefault(); var form = $('form').serialize(); image_form = $("#id_image")[0].f ...

A guide on effectively mocking a Vuex store within the parentComponent of VueJS test-utils

I am currently using Jest in conjunction with vue-test-utils to test the reaction of a child component to an $emit event triggered by the parent component. The VueJS test-utils library offers a parentComponent option that can be utilized when mounting or ...

The border-radius property in Bootstrap buttons causes unwanted white border artifacts to appear

Strange anomalies in the borders of my Bootstrap buttons caught my attention recently. Upon further investigation, I realized that this issue is not linked to my custom styles or theme, as the artifacts can also be seen on the Bootstrap button documentatio ...

Sass Alert: The mixin called roboto-family is missing from the stylesheet. Trace: Problem detected in src/pages/forms/forms.scss at

Greetings, I am diving into the world of Ionic for the first time. Recently, I embarked on a new project in Ionic and decided to integrate a theme. To do so, I copied an .html file, an .scss file, and also created a .ts file. Forms.html <!DOCTYPE html ...

Attempting to deactivate expired cards

Hello everyone, I could really use some assistance. I am trying to map items with a specific property called 'expired' and I want each card to render in a disabled state. However, I'm struggling to achieve this using MUI components. Here is ...

Why is it that a static variable cannot be accessed using the `this` keyword in a static method when the static method is called in any route's controller in NODEJS?

Is it possible to access static variables in a static method using the 'this' keyword? The answer is yes, but there seems to be an issue when passing that static method in any route. The 'this' keyword refers to the class, yet its value ...

React safeguarding sensitive data in production builds

In the process of developing a React app with Docker and Jenkins for deployment, one question arises: How can I securely provide environment variables to this static application? Shown below is my current Dockerfile: # Stage 1: building the React app FRO ...

Node_modules folder is excluded from Typescript compilation

I am struggling to understand why TypeScript is not compiling code from the node_modules folder. Below is the content of my tsconfig.json file: { "compilerOptions": { "rootDir": ".", "baseUrl": ".", "paths": { "shared": ["./src/shared ...

JavaScript to resize images before uploading without displaying a preview

I'm searching for a way to prevent the need to upload large or heavy image files. I believe utilizing the HTML5 FileAPI library is the best solution for this task. All necessary features have been implemented (upload, re-ordering, etc.), so now I ju ...

Issue with React Routes only occurring in the production website

I'm encountering an issue on my personal website that only occurs in production, but not in my local environment. Here's the situation: I have set up the routes as follows const Routes = () => ( <Router> <Route exact path=&quo ...

Creating a React Swiper that dynamically centers a sliding element of varying width

I am currently working on a carousel where the center slide needs to expand to display additional content. I have set up a working example in this codesandbox. The main criteria for this project are: Non-centered slides will be minimized to show only the ...

Building upon the preceding inquiry, a ReferenceError has occurred due to the object being undefined

After researching online, I came across a similar question marked as a duplicate that brought me to this link: How do I return the response from an asynchronous call?. Even though I couldn't find a solution in that thread, it seems like I may need to ...

Is it possible to apply identical css styles to multiple ids at once?

Is there a way to accomplish this? .apple, .orange, .kiwi h1 {color: #892828;} I'm having trouble making it work. Any suggestions? ...

Utilize three.js to set the camera's position and rotation

In my current setup, I have a particular object in view using a PerspectiveCamera. By utilizing OrbitControls, I can navigate around the object, rotate it, pan it, and more. My goal is to reposition the object to a specific location at a specific angle an ...

What is the best way to display a unique modal on every tab?

I'm facing an issue where I am attempting to trigger a modal on each tab item, however the modal only opens on the initial tab. Clicking on any other item results in the modal opening on the first tab instead. Additionally, when I add new items, I am ...