Creating a customized conditional overflow style in _document.js for Next.js

Is there a way to dynamically change the overflow style for the html and body elements based on the page being viewed?

For instance, on the about page, I want to hide overflow for html but not for body, whereas on the contact page, I want to hide overflow for body but not for html.

This issue arose when I switched from using vanilla CSS to the Next UI library halfway through the project. I am looking for a quick solution, even if it involves a bit of a hack.

Here is an example of some pseudocode I have tried:

<Html lang="en" style={if (aboutpage) { overflow: "hidden" } else { overflow: "scroll" }}>
  <Head>{CssBaseline.flush()}</Head>

import React from 'react';
import Document, { Html, Head, Main, NextScript } from 'next/document';
import { CssBaseline } from '@nextui-org/react';
import { useRouter } from "next/router";


class MyDocument extends Document {
  static async getInitialProps(ctx) {
    const initialProps = await Document.getInitialProps(ctx);
    return {
      ...initialProps,
      styles: React.Children.toArray([initialProps.styles])
    };
  }

  render() {
    return (
      <Html lang="en" style={{ overflow: 'scroll' }}>
        <Head>{CssBaseline.flush()}</Head>
        <body style={{ overflow: 'hidden' }}>
          <Main />
          <NextScript />
        </body>
      </Html>
    );
  }
}

export default MyDocument;


Any suggestions or advice would be greatly appreciated!

I attempted to create some pseudocode, but I am struggling with implementing a conditional statement to change the style of the Html tag and Body element.

Answer №1

To easily update the overflow properties of the html and body elements, you can use the useEffect() hook on the specific pages you choose. For instance, on your about page, you can implement the following code:

// Example for the about page
useEffect(() => {
    document.documentElement.style.overflow = "hidden";
    document.body.style.overflow = "scroll";
}, []);

Once the page is initially rendered, you have the freedom to customize the styles of the documentElement (html tag) and the body element however you prefer.

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

What is the best way to test a callback function of a React component that is encapsulated with withRouter()?

In my Jest and Enzyme testing of a TypeScript-written React project, I have a component wrapped in a React-Router router. Here's a snippet of the code: import { SomeButton } from './someButton'; import { RouteComponentProps, withRouter } fr ...

I'm wondering why my second div is displaying a different size compared to the rest, even though they all share the same container-fluid class

Within the HTML snippet provided, utilizing Bootstrap, all three child divs possess the container-fluid class. However, why does the 2nd div differ from the others? Refer to this example Div Example. Div1 and div4 exhibit the same characteristics, as do d ...

Can I invoke an actions function within my reducer using an Express route?

In my Express route, I want to call an action function imported from my reducer: /* initial state */ export var usersStartState = { isAccountVerified: false, }; /* action types */ export const actionTypes = { IS_ACCOUNT_VERIFIED: 'IS_ACCOUNT_VER ...

Tips for securely integrating freelancers into your web project

Looking for a secure way to bring in freelancers to assist with tasks on our website, where the freelancer only has write access to specific pages. I'm aware that this can be done with tools like Windows Team Foundation Server. However, I need the fr ...

What is the best way to vertically center a column of images on mobile devices in a responsive manner?

Currently, I am developing an application that showcases the 9 newest photos with a specific tag. To ensure consistency in image sizes, I have set each photo to be 240px wide and 200px tall. My query now is how can I vertically center these images so they ...

The Vue.js scripts and styles declared in the index.html file seem to be malfunctioning

I acquired a theme that includes html, css3, and js files, and I included the file path as shown below: <!-- Basic --> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title>Porto - Responsive HTML5 Te ...

Filtering properties of objects in Vue

I am currently dealing with an array of objects that represent continents: data() { return { continents: [ { name: "South America", countries: [ { name: "P ...

Is it possible to compare two charts in Chart.js in a way that avoids the issue of small values appearing as large as big values?

I am currently working on a production tracking page that features multiple charts. I want to avoid inconsistencies in tracking at first glance. Is there a way to achieve this using chart.js? If not, what would be the best approach to address this issue? ...

Troubleshooting a unique CSS problem on an Android PhoneGap

We are currently working on an Android application using PhoneGap, HTML, CSS, and jQuery Mobile. After compiling the application in Eclipse, everything seems to work correctly. However, I am facing an issue where my CSS styles are not updating when recompi ...

Is there a way to include a different component without it automatically displaying within a div element?

Is there a way to make the Torrent component render without directly binding it to a DOM element? I am facing an issue with my Torrent Table Component as I want it to be populated with Torrent Components based on API data, but it's not rendering beca ...

Issues with compiling Vuetify SASS in Nuxt for incorrect output

I am trying to integrate Vuetify with Nuxt using a Plugin but I am encountering the following issue: https://i.sstatic.net/KZbCN.png Error Message: ERROR in ./node_modules/vuetify/src/components/VProgressLinear/VProgressLinear.sass ...

We were unable to identify any Next.js version in your project. Please ensure that the `"next"` package is installed in either the "dependencies" or "devDependencies" section

My attempt to deploy a Next app using the Vercel CLI has hit a roadblock. After running vercel build with no errors, I proceeded to deploy with vercel deploy --prebuilt, which also went smoothly. However, when trying to move the project from the preview en ...

Ways to update the div's color according to a specific value

Below are the scripts and styles that were implemented: <script src="angular.min.js"></script> <style> .greater { color:#D7E3BF; background-color:#D7E3BF; } .less { color:#E5B9B5; background-co ...

Tips for Deactivating One Button While Allowing Others to Remain Active

Whenever the $order_status is marked as Accepted, only the button labeled Accept should be disabled. If the $order_status changes to Dispatched, then the button that should be disabled is labeled as Sent. However, if the status is Cancelled, then the butto ...

Retrieve the .blob file stored on your device

While working on crafting a birthday gift for a friend, I came across an IPA file which I unzipped, only to discover that the picture assets I needed were packed inside a .blob file. While analyzing the hex representation of the file, it appears that the i ...

Using Angular to make an API call within a JavaScript function

I am facing an issue when trying to call an API in a JavaScript function as shown below. The injected services (subService) and defined variables (formData) are not recognized in the JavaScript function, resulting in an error of undefined addSub. How can I ...

Using three.js to establish an Image for Particle

I am looking to make some changes to this demo: Instead of having colored particles, I want to assign an image to each one. Should I use a cube for this purpose? Or is there a way to use an image with Vector3? Here is the code for the example: i ...

I'm running into an issue with my React component where it is rendering before the state is set, causing it to fail. Is there a

Is it possible for me to achieve what I've been attempting for the past week? I feel like I'm so close, yet still can't quite reach my goal. Could it be that what I'm trying to do is impossible? I am using reactjs and next js (although ...

Guide to invoking the NPM request multiple times within the mocha before hook

Can anyone advise on the correct way to call request multiple times (2 times) in mocha before hook? I am currently facing an issue where I get an error saying 'done() called too many times'. describe('...', function(){ before(functio ...

Behavior of routing not functioning as anticipated

In my app-routing.module.ts file, I have defined the following routes variable: const routes: Routes = [ { path: '', redirectTo: '/users', pathMatch: 'full' }, { path: 'users', component: UsersComponent }, ...