The functionality to scroll to the top of the page is not functioning properly in Next.js when navigating to a new page using the Link

While using Next.js, I encountered an issue where opening a new page would maintain the scroll position from the previous page. For instance, if I had scrolled to the bottom of a product listing page and clicked on a specific product, the product details page would open with the scroll position still at the bottom.

I am seeking a solution to automatically scroll to the top when navigating to a new page in Next.js. How can I implement this scroll-to-top functionality?

Below are some approaches I have attempted:

Attempt 1

import { useEffect } from 'react';
import { useRouter } from 'next/router';

const ProductDetails = () => {
    const router = useRouter();

    useEffect(() => {
        const handleRouteChange = () => {
            window.scrollTo(0, 0);
        };

        router.events.on('routeChangeComplete', handleRouteChange);

        return () => {
            router.events.off('routeChangeComplete', handleRouteChange);
        };
    }, [router]);

    return (
        // Product details code goes here
    );
};

export default ProductDetails;

Attempt 2

import { useEffect } from 'react';
import { useRouter } from 'next/router';

const ProductDetails = () => {
    const router = useRouter();
    
    useEffect(() => {
        window.scrollTo(0, 0);
    }, [router.pathname]);
  
    return (
        // Product details code goes here
    );
};

export default ProductDetails;

Attempt 3

import { useEffect } from 'react';
import { useRouter } from 'next/router';

const ProductDetails = () => {
    const router = useRouter();
    
    useEffect(() => {
        window.scrollTo(0, 0);
    }, []);
  
    return (
        // Product details code goes here
    );
};

export default ProductDetails;

Attempt 4

useEffect(() => {
   // The scrollTo behavior is set on the container element with the id "top"
   const topElement = document.getElementById("top");
   topElement?.scrollIntoView({ behavior: "smooth" });
}, [router.pathname]);

The solutions above worked for other routes, but they did not work for dynamic routes like /products/product/[slug], even when adding the slug to the dependency array in useEffect.

Note: I also tried placing the code directly into the component where I wanted the screen to scroll to the top, but it did not achieve the desired outcome.

Edited: Code example added for reference

Answer №1

After much exploration, I stumbled upon a solution that brought a smile to my face.

The issue wasn't with the Next.js components themselves. It turned out to be a problem with the predefined CSS in the global.css file.

By default, Next.js' global.css includes a significant amount of CSS code. One particular section defines styling for the body and HTML tags:

html,body {
  max-width: 100vw;
  overflow-x: hidden;
}

Once I removed the overflow-x: hidden from the html/body rule, everything started functioning as expected.

I want to express my gratitude to @divine for their insightful answer on a separate Stack Overflow question addressing the same issue. You can find their response here.

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

The clear function in the template slot of Vue multiselect is not functioning properly

I decided to incorporate the asynchronous select feature found in the documentation for my project. This feature allows me to easily remove a selected value by clicking on 'X'. Below is a snippet of the general component that I use across variou ...

Creating a highly innovative server infrastructure tailored for Dojo applications with exceptional features

Recently, I have been using web2py for my projects and have found it incredibly useful in creating RESTful web applications. However, I am now looking to expand my skills in JavaScript by developing a more modern and dynamic client-side application that re ...

Python's Selenium encountering a NoSuchElementException with the error message "./ancestor-or-self::form"

Trying to create a Python script that allows me to input my credentials and tweet text in the Python console. The script should then log in and post a tweet using Selenium. Everything works fine, except for the final click on the Tweet button which is caus ...

typescript tips for incorporating nested types in inheritance

I currently have a specific data structure. type Deposit { num1: number; num2: number; } type Nice { num: number; deposit: Deposit; } As of now, I am using the Nice type, but I wish to enhance it by adding more fields to its deposit. Ultima ...

When it comes to using jQuery, I find that it only functions properly when I manually input the code into the Google Chrome console. Otherwise

Below is the HTML snippet: <textarea cols="5" disabled id="textareRSAKeypair"> @Model["keypair"] </textarea> <a href="#" class="btn btn-primary" id="downloadKeypair">Download Key</a> Here is the jQuery code: <script src="ht ...

Browsing through different backdrop visuals

I realize this question has been brought up numerous times before, but I urge you to take a moment and read through it. Currently, I am looking to add more interactivity to my HTML page. My goal is to change the background image every five seconds with a ...

Steps for eliminating double quotes from the start and end of a numbered value within a list

I currently have the following data: let str = "1,2,3,4" My goal is to convert it into an array like this: arr = [1,2,3,4] ...

Having difficulty accessing the value of a table td element in HTML using a jQuery selector

When creating a table, I utilize ng-repeat to generate table rows. Whenever the dropdown changes, a function is triggered which applies certain conditions. Based on these conditions, an object is added to an array that is bound to a scope variable. Here i ...

React Native animation encountered a rendering issue: Invalid transform scaleDisliked value: { "scaleDisliked": 1 }

While working on my react native app, I encountered an issue when trying to apply a transform:scale effect to an Animated.View component. I am using interpolate for this purpose, but unfortunately, I keep receiving the following error message: Render error ...

Retrieving the value of the option that has been selected from a dropdown

I have successfully implemented a drop-down menu with the following code: // Creating a select element for priority within a form in the bottom row div const formPriority = document.createElement("select"); formPriority.setAttribute("name","project"); form ...

JavaScript can be utilized to alter the style of a cursor

I'm currently developing a browser game and incorporating custom cursors into it. To ensure the custom cursor is displayed throughout the entire page, I've applied it in my CSS (though setting it up for 'body' occasionally reverts back ...

Adjust background color on click using JavaScript

Could someone provide me with the JavaScript code to change the background color of a page from blue to green when a button is clicked? I have seen this feature on many websites but haven't been able to write the code myself. I am specifically lo ...

How can I swap out the text within an anchor tag using jQuery?

I am working with the following HTML structure: <div class="event tiny"> <a href="/whatever">Something</a> </div> My goal is to change the text of this link to "Anything" … However, when I try the following code: $('. ...

AngularJS Bootstrap Datepicker populating date from input field

I'm currently utilizing Bootstrap for my web application. I've developed a method that initializes all input fields of type date with a class called form_datetime: function initDatepicker(){ $(".form_datetime").datepicker({ ...

Navigating through Next.js for slug URLs such as site.com/username

Can someone help me figure out how to create a profile page for each username, like site.com/jack or site.com/jill? I'll be pulling the username info from an API that also contains the user ID and email. I'm new to Next.js and would really appre ...

How to Dynamically Set AngularJS Filter (like date or currency) Using Variables

When working with Angular, it's possible to easily apply filters to format variables, like so: {{ myDate | date }} {{ myMoney | currency }} But, is there a way to dynamically set the filter type in a more flexible manner as shown below? // controll ...

I am currently working on a project using ar.js

I came across a glitch code that triggers a video when scanning the marker. However, I encountered an issue where it only works on desktop. On Chrome for Android, the video does not appear, only the sound can be heard. I need assistance as my coding knowle ...

Troubleshooting Compatibility Issues: JavaScript Function Works in Chrome but not in Internet

After collaborating with fellow coders to develop info boxes using HTML, CSS, and JavaScript, I have come across an issue with the hover functionality not working properly in Internet Explorer. Interestingly, everything functions flawlessly on Google Chrom ...

Using Javascript Regular Expressions to validate that the first number in an amount is non-zero

Need a solution to only accept numbers that do not start with zero, but can contain zeros after the first digit. Currently using var.replace(/[^1-9]/g, ''); which prevents input of 0 altogether. Examples of valid inputs: 10 9990 Examples of in ...

What is the best way to generate an @ symbol using JavaScript?

When coding in Javascript, a challenge I am facing is creating a variable that includes the @ symbol in a string without it being misinterpreted as something else, especially when dealing with URLs. Does anyone have any suggestions on how to handle this ...