Prevent scrolling on body while mobile navigation is activated in Next.js

Normally, disabling scrolling on the body element can be achieved by toggling a class or overflow property when a mobile menu or modal is open. However, due to Next.js being rendered server-side, accessing the document object is not possible. How can I prevent body scroll when the mobile navigation menu is open in Next.js?

I attempted to access the document object to toggle overlay hidden, but because Next.js is rendered server-side, the document object is unavailable at that stage.

I also experimented with using state and passing it into the navigation component to control the styles, but encountered an issue as useState cannot be used at the top level of the application.

Answer №1

Utilizing a useEffect hook, I made sure that the code is executed only after the component has finished loading. The mobile menu state was set as a dependency to control the behavior of the document body's overflow property.

useEffect(() => {
  mobileNav
    ? (document.body.style.overflow = 'hidden')
    : (document.body.style.overflow = 'auto');
}, [mobileMenuState]);

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

Error encountered while trying to import the Turborepo UI package into Next.js: It appears that an appropriate loader may be required

Currently, I am working on a project using next.js 13.1.1 and setting up a monoRepo-based project with turborepo for the first time. My goal is to incorporate: @next/bundle-analyzer @sentry/nextjs @next-pwa When these configurations are not used, everyth ...

How can you use React.js to only display "Loading..." on the page while the full name is included in the URL?

I've hit a roadblock while trying to solve this issue. Here's the situation: On the page where I need to display certain information, I intended to showcase the full name of the individual from a previous form submission. However, instead of seei ...

Load a file in JavaScript without using the cache

I'm working on a function that reads a text file from a specific location: <html> <head> <script> function readTextFile(file){ var out_text='' var rawFile = new XMLHttpRequest(); rawFile ...

Django Vue3 encounters access-control-allow-origin restriction

I am currently working on a Django rest-api project that uses Vue on the front-end. Unfortunately, I encountered an error while making requests via Vue: Console output: The following error is displayed: Access to XMLHttpRequest at 'https://api.iyziw ...

Issue with displaying the glyphicon-chevron on the carousel control

Currently, I'm in the process of incorporating a straightforward modal into my gallery design. I have a slide carousel positioned at the top of the page, while at the bottom, there are thumbnails of the gallery. While the slide carousel control butto ...

Having trouble with an unknown cipher when using the crypto module?

Encountering difficulty encrypting with aes-256 using cipher - getting an error stating unknown cipher. Any insights on what may be missing in the code below? index.js function encryptPaymentId(specialtyID, paymentId) { const convertToStrin ...

Access remote web page within bootstrap modal

Dealing with a recurring issue, I am trying to create a modal that opens content from a remote page populated by a MySql database. Custom styling is also required for the modal. Progress has been made, but now I'm stuck. Below is the current code: Ou ...

Using a checkbox to sort through Google Maps markers

I want to create a filter for my google maps markers using checkboxes, inspired by this V3 example. Here's the HTML for the checkboxes: <form action="#"> Attractions: <input type="checkbox" id="attractionbox" onclick="boxclick(this,'a ...

How do I use regex to grab all the text between two specific headers?

I need help extracting text between two specific headings. I attempted to create a regex for this purpose, but it's not quite capturing what I want. Currently, it includes the heading and paragraph, but misses the last heading. My Current Regex: /^& ...

Can data sent to php via ajax be manipulated?

To restrict the number of characters a user can input in a textarea, I have implemented a character counter. // part of tinymce setup: function (ed) { ed.on('keyup', function (e) { var maxchars = <?php echo $max_chars_allowed; ?>; ...

Should reports be created in Angular or Node? Is it better to generate HTML on the client side or server side

I have a daunting task ahead of me - creating 18 intricate reports filled with vast amounts of data for both print and PDF formats. These reports, however, do not require any user interaction. Currently, my process involves the following: The index.html ...

A method for dividing a string into separate characters and organizing them into an array of JSON objects

I have a collection of JSON objects with a fixed key 'type' and additional keys based on the type. Here is an example of how it looks: theArray = [ { "type": "text", "text": "= SUM(" ...

The host name specified in the _document.js file within a NextJS project

Is it possible to obtain the hostname in the _document.js file within nextJS without access to the window object during server-side rendering? I attempted to retrieve it from initialProps (context), yet the req in initialProps remained undefined. Are the ...

MongoDB does not treat aggregate match pipeline as equal to in comparisons

I've been tackling an aggregate pipeline task for MongoDB where I need to retrieve items that do not have a specific user ID. Despite my efforts, I'm struggling to get it right. I attempted using $not, $ne, and $nin in various ways but couldn&ap ...

Determine if the current window has already been opened using JavaScript

I am exploring ways to determine if the current page is open in another tab. After attempting to use window.open(), I found that it returns the current window rather than a different window with the same address. This results in always returning true. Fo ...

What sets `isomorphic-fetch` apart from `isomorphic-unfetch` in the world of npm packages?

Both Isomorphic Unfetch and Isomorphic Fetch are used for server-side rendering. But what sets them apart? Aside from the fact that Isomorphic Fetch is older and slightly larger when gzipped according to this comparison. Learn more about each library here ...

Guide to playing a gif solely through an onclick event using JavaScript

Below you will find a code that is used to load a gif animation from an array of characters, and then display it within a board class using the image src. I am looking to make the gif animation play only when the displayed gif is clicked. Currently, the ...

Slowly soften images following a brief pause

Hey there! I have a little project where I am trying to rotate images within a div every few seconds The code I currently have is functional, but there are a couple of things that I want to tweak and I'm hoping you can assist me with that: The di ...

Going through each file individually and addressing any issues

I have a folder with hundreds of files that I need to read. Currently, my method reads all the files at once and returns the content as an array. However, I want to optimize this process by reading one file at a time and sending it to the client before mov ...

Prevent tooltip text from appearing when a button is disabled in an angular application

As a beginner in UI development, I have a requirement for my Angular application. I need to enable and disable a button based on certain conditions. The tricky part is that I want to display a tooltip only when the button is enabled. I have managed to chan ...