Tips for preventing background scrolling of a Fixed element in React

Currently, I am working on a project using NextJS with Tailwind CSS. I am in the process of creating a drawer, popup, and modal with the CSS property position: fixed. However, I have encountered an issue where when I scroll on the fixed elements, the background also scrolls. Even if the fixed element is scrollable, once the scroll ends, the background starts to scroll. How can I prevent this behavior and make the background non-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>
  );
}

Answer №1

When using the Modal component, make sure to include this useEffect function. If you are incorporating tailwind-css, remember to add the overflow-hidden className to the body element.

useEffect(() => {
    // Disable scrolling on the previous page
    document.body.classList.add("overflow-hidden");
    // Remove the class when the modal is closed
    return () => {
      document.body.classList.remove("overflow-hidden");
    };
  }, []);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Any tips on incorporating styled-components and local fonts in Next.js?

Recently, I integrated styled-components into my Next.js application. To make it work, I had to include a Babel file with the following code: { "presets": ["next/babel"], "plugins": [["styled-components", { "ssr": true ...

Node and Express are correctly logging the response, however the React frontend is logging an entirely different message

Currently, I am in the process of developing a form for an eCommerce platform that allows the administrator/owner to upload images to Cloudinary. At the moment, the image is being successfully uploaded to Cloudinary. Upon logging the response (using conso ...

Modify CSS progress circle to update the percentage of completion

I stumbled upon this code snippet, and although it works flawlessly, I encountered a limitation - I can only set the percentage to 25, 50, or 75. If I try to increase it to 85%, the circle fills up completely. Does anyone have any suggestions on how to res ...

Textarea is limited to resizing just one specific area

I've been experiencing issues with my textareas. The problem arises when I try to have multiple textareas that need to resize on page load. It seems to work well for the first textarea, but as soon as I insert another one, only the first one responds ...

Fresh React framework

I haven't worked on a React app in a while, but when I decided to start a new one and import my old function, I encountered the following error: C:/Users/Hello/Documents/Dev/contacts/client/src/App.tsx TypeScript error in C:/Users/Hello/Documents/Dev ...

Struggling to make antd compatible with my create-react-app project

Exploring ant.design with create-react-app piqued my interest, so I decided to follow the steps outlined in the antd documentation. https://ant.design/docs/react/use-with-create-react-app npx create-react-app antd-demo npm add antd Within the app.js fil ...

Error 404: Next.js Navigation Not Detected

I've recently launched a new Next.js project and I'm currently working on implementing client-side navigation. However, I am facing an issue where I am unable to navigate to routes other than "/". Layout.js : import "../styles/globals.css&q ...

Understanding the relationship between JavaScript UI components and their impact on HTML is essential in grasping

Many JavaScript UI components, such as jQuery UI, Bootstrap, or Kendo UI, take an HTML element and dynamically render themselves. For example: $('#someselect').autocomplete(); I am curious if these frameworks can be successfully integrated wit ...

What is the best way to navigate my Page while my Dialog Component is displayed?

Is there a way to enable scrolling on the background when a dialog component opens up? By default, scrolling is disabled when the dialog appears. How can we allow scrolling in the background? Here is the code snippet: import React, { useState } from &apos ...

I am facing an issue in my Nextjs project where the Array Object is not being properly displayed

Hi there! I am new to Nextjs and currently learning. I recently created a component called TeamCard which takes imgSrc, altText, title, designation, and socialProfile as parameters. However, when attempting to display the socialProfile object array using m ...

Click functionality being incorporated into Material UI

I need assistance with incorporating an onClick event handler in a material ui example, but it doesn't seem to be working as expected. <Tooltip title="Filter list"> <IconButton aria-label="Filter list"> <FilterListIcon/> </ ...

An unexpected error occurred during runtime: Failed request with status code 500 in NextJS

I've been following a tutorial on cloning Amazon and despite having the same code as in the video, I keep encountering an error. I generated new keys for Firebase and Stripe, and even adjusted the Shipping Rates in Stripe. The error message can be see ...

Footer remains attached to the bottom of the page while the content extends too far down

Having some trouble with my sticky footer - despite checking out various resources and examples, I can't seem to achieve the desired outcome. Update: I don't want the footer to be fixed. I want it to stay at the bottom of the screen if there isn ...

Concentrate on a specific input within a list of inputs that are generated dynamically

My list contains dynamically generated inputs. input --> onClick new Input beneath [dynamically added]input input How can I focus on just the dynamically added input? The input has the textInput reference. This code partially achieves it: componentW ...

Encountering an issue in React: Uncaught ReferenceError - require function not recognized

I am currently working on a project that utilizes both react and node (express). When I include react using src="https://unpkg.com/react@16/umd/react.development.js", everything works fine with JSX in the project. However, when I attempt to import like thi ...

The declaration file for the module 'react-tilt' was not located

After following the installation and import steps for react-tilt as outlined in this guide, I encountered the following error message and am unable to utilize it. I'm uncertain about what the message implies. Is there anyone who can help me resolve th ...

Center align the image without any additional spaces

https://i.sstatic.net/Oxmqa.pngI'm looking to center align the logo within the navigation bar on my page. Here is the code I currently have: <div class="nav"> <ul> <li id="center"> <a href="home.php">&l ...

`Although useMediaQuery does not function properly in the top-level React component, it works perfectly fine when used in

Recently, I encountered an issue while using useMediaQuery from Material UI in my React application. Initially, I had placed the query in the top-level component (App) of my app, but it did not function correctly. The value did not update upon window resiz ...

Struggling to update state in React despite attempts to modify the state

Even though I have set the defaultAccount state to the metamask account, when trying to print it in the code below, it still shows null. The issue arises with fetching the value of defaultAccount. (Please see the error image below) class App extends Compo ...

ESLint prohibits the usage of React.StatelessComponent and React.FunctionalComponent within the codebase

Is there a way to restrict the use of React.StatelessComponent or React.FunctionalComponent and only allow React.FC in my code? For instance: export const ComponentOne: React.StatelessComponent<Props> = (props) => { return <....> }; export ...