In React, how to prevent body from scrolling when a modal is opened

wwayne
Yet SH
Published in
2 min readSep 25, 2018

--

In HTML, modal usually refers to an element with the following CSS:

position: fixed;
top: 0;
right: 0;
bottom: 0;
left: 0;
z-index: 999;

However, scrolling inside a modal will lead to body scrolling which is kind of annoying. I searched on the internet but didn’t find a perfect solution(especially for React), so I did some experiments and found a solution which works well in Chrome, Firefox and Safari.

How I define and use the Modal component

I just wanna do a quick explanation of how I define my Modal component for a better understanding, you can skip this section if you only interesting in the final solution.

React Frontend structure:

components/
Modal/
index.js
pages/
MyPage/
index.js

How to invoke Modal in a page:

Final Solution

  • when opening the modal, set the document.body as position: fixed and set its offset based on the current scrolling. If only applied position: fixed, the body will scroll to the top, so we need to make the body align with its previous offset manually.
  • when closing the modal, clean the style on the document.body and scroll the body to the previous position. If only clean the style, the body will start from the top, that’s why we have to make use of window.scrollTo to scroll the body to the previous offset.

About Yet

Yet is an online tool which helps people to build one-page business website without any code and design required.

--

--