Home > Blockchain >  I do not want scrolling to be possible when the cart overlay is opened
I do not want scrolling to be possible when the cart overlay is opened

Time:08-27

When the user opens the cart overlay, scrolling of the background shouldn't be possible. I have searched and i can't seem to find a workable way around it. Here's the code.

class CartMenu extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      open: false,
    };
    this.dropdownRef = React.createRef();
  }

  componentDidMount() {
    this.props.setCartCloseFunc(this.closeMenu);
  }

  setOpenOrClosed() {
    this.setState(
      (prevState) => ({ open: !prevState.open }),
      () => {
        this.props.onCartButtonClicked(this.state.open);
      }
    );
  }

This is a snippet of the code. Is there a workaround?

CodePudding user response:

  1. Get the root html element of your app (usually with id="root")
  2. Then when your cart is open, set the root element a overflow: hidden css
  3. And when it's false, set it back to unset

CodePudding user response:

As I understand you problem, you are in a React environment. What you need here is to make the body not scrollable anymore. Fortunately for you, body isn't in the scope of React, only what's in div#app is (if I remember the basics of React).

You basically need to toggle the overflow: hidden state of the body element, by using JS, or CSS and JS.

Only JS

Using only JS, you need to use this:

// to block the scroll
document.body.style.overflow = "hidden";

// to make it scrollable again
document.body.style.overflow = "unset";

JS and CSS combined

If you prefer using a class toggle and CSS, you can use the classList API.

// to block the scroll
document.body.classList.add('no-scroll');

// to make it scrollable again
document.body.classList.remove('no-scroll');

with this CSS

body.no-scroll {
    overflow: hidden;
}

Good to know

I know some version of mobile OS doesn't like this way. If you want, you can do the same with this small library: body-scroll-lock

I hope I could help

  • Related