#JavaScript #Reactjs - How to prevent background scrolling when modal / overlay / popup is up?

To prevent background scrolling when a modal / overlay / popup is on, you can temporarily set body's overflow to hidden. After you close the modal, reset the body's overflow to initial.

To have your modal content scrollable, you set its container's overflow to scroll.

Screenshots of my portfolio

Project view
Portfolio overlay
Portfolio overlay

Overlay predecorated

Sample Code - React

// modalContent styled-component way
// note that modalContent is inside a div that has position fixed and z-index set
export const modalContent = styled(Relative)`
  background-color: ${red};
  width: 0vw;
  height: 100vh;
  overflow: scroll;
  padding-top: 7em;

// onClick function to open up a modal 

toggleModal(openModal) {
  if (openModal) {
    document.querySelector('body').style.overflow = 'hidden';
  } else {
    document.querySelector('body').style.overflow = 'initial';
    showModal: openModal

Thank you for reading!