In React, how to prevent body from scrolling when a modal is opened
In HTML, modal usually refers to an element with the following CSS:
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:
How to invoke Modal in a page:
- 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.
Yet is an online tool which helps people to build one-page business website without any code and design required.