Home > Software design >  How to stop background scroll of Fixed element in React?
How to stop background scroll of Fixed element in React?

Time:12-25

I'm using NextJS with tailwind. and I'm creating a drawer, popup and modal with position: fixed. so when i implement this and scroll on it the background component will scroll as well. even if the fixed is scrollable when the scroll end the back element starts to scroll. how can I make it stop for the background to be not scrollable and clickable?

function Drawer() {
  const toggle = useSelector(selectMenu);
  const dispatch = useDispatch();
  const handleOnClose = (e) => {
    if (e.target.id === "container") dispatch(toggleMenu(!toggle));
  };
  return (
    <div
      id="container"
      onClick={handleOnClose}
      className={`md:hidden h-full w-full backdrop-blur-sm fixed ${
        !toggle && "hidden"
      }`}
    >
      <div
        className={`${
          toggle ? " translate-x-0" : "translate-x-full"
        } md:hidden fixed h-screen w-3/4 ease-in-out duration-300 bg-white z-50 bottom-0 top-0 right-0 flex flex-col px-4 py-3 space-y-5 shadow-2xl`}
      >
        <Link
          href="/"
          className="cursor-pointer flex px-2 space-x-4"
          onClick={() => dispatch(toggleMenu(!toggle))}
        >
          <HomeModernIcon className="h-6 w-6 text-black" />
          <h1>Dashboard</h1>
        </Link>
        <div className=" h-[1px] w-full bg-gray-600" />
        <Link
          href="/clients"
          className="cursor-pointer flex px-2 space-x-4"
          onClick={() => dispatch(toggleMenu(!toggle))}
        >
          <TruckIcon className="h-6 w-6 text-black" />
          <h1>Clients</h1>
        </Link>
        <div className=" h-[1px] w-full bg-gray-600" />
        <Link
          href="/employee"
          className="cursor-pointer flex px-2 space-x-4"
          onClick={() => dispatch(toggleMenu(!toggle))}
        >
          <PuzzlePieceIcon className="h-6 w-6 text-black" />
          <h1>Employee</h1>
        </Link>
        <div className=" h-[1px] w-full bg-gray-600" />
        <Link
          href="/services"
          className="cursor-pointer flex px-2 space-x-4"
          onClick={() => dispatch(toggleMenu(!toggle))}
        >
          <WrenchIcon className="h-6 w-6 text-black" />
          <h1>Services</h1>
        </Link>
      </div>
    </div>
  );
}

CodePudding user response:

Inside Modal component add this useEffect. since you are using tailwind-css, add overflow-hidden className to the body element

useEffect(() => {
    // this will disable the scroll if our back page was scrollable
    document.body.classList.add("overflow-hidden");
    // when you close the modal, remove this class 
    return () => {
      document.body.classList.remove("overflow-hidden");
    };
  }, []);
  • Related