reactjsscroll-position

Restore scroll position after toggled a modal in react with useContext


Goal

Restore the scoll position of the window after the a div has toggled from position fixed to none.

Problem

Restoring the scroll position doesnt work although i get it saved correctly to the state.

Description

I have a page where a modal is opened via onClick. Therefore i created a "ToggleModalContext" to pass the props to the modal on the one hand and to the background div on the other hand. I want to modify the background div with setting the css property position to fixed to avoid that the background is scrolled instead of the content of the modal. When the modal is closed, the position: fixed is removed and i want to restore the scroll position of the window. This last step doesnt work. Maybe someone else has an idea?

ToggleModalContext (Thats the context, where the scroll restore function is called)

import React from "react";

export const ToggleModalContext = React.createContext();

export const ModalProvider = props => {
  const [toggle, setToggle] = React.useState(false);
  const [scrollPosition, setScrollPosition] = React.useState();

  function handleToggle() {
    if (toggle === false) {
      setScrollPosition(window.pageYOffset); // When the Modal gets opened, the scrollposition is saved correctly
    }
    if (toggle === true) {
      window.scrollTo(0, scrollPosition); // Restoring doesnt work. 
    }

    setToggle(!toggle);
  }

  return (
    <ToggleModalContext.Provider value={[toggle, handleToggle]}>
      {props.children}
    </ToggleModalContext.Provider>
  );
};

Maybe somebody has a idea? Maybe i have to use useEffect? But how? Thanks for your time in advance :)


Solution

  • From the description you have provided, you are using a fixed position on the background div to remove scrolling on the window when you open your modal

    On the other hand, you are calling

    if (toggle === true) { window.scrollTo(0, scrollPosition);}
    

    before your modal has closed. At this time, the background div is in a fixed position and there is no where to scroll to.

    You need to ensure that your modal has safely closed and your background div is back to its normal position before calling this function. To see the behavior, you can use a setTimeout function and call this function there with a set time e.g.

    setTimeout(() => window.scrollTo(0, scrollPosition), 2000);