What is the best way to navigate back to the top of the page once a link has been clicked?

One issue I'm facing is that whenever I click on a link in NextJS, it directs me to the middle of the page:

<Link href={`/products/${id}`} key={id}>
   <a>
      {/* other components */}
   </a>
</Link>

I believe the problem lies in the fact that the link is positioned in the center of the page. When clicked, it remains at the same position instead of scrolling to the top. It may sound odd, but that seems to be what's happening.

I've attempted various solutions such as including scroll={true} or scroll={false} in the <Link> tag. I've also tried applying height: 100% to html and body in CSS. Additionally, I experimented with scroll-behavior: smooth; and other methods, yet the issue persists.

Here's a video demonstrating the problem: https://drive.google.com/file/d/1CCgFCJb1fl9RRYmW5yp41US-0yuSqpfj/view?usp=sharing

A temporary workaround is to avoid using <Link> and stick to the traditional <a> tag. Unlike <Link>, the <a> tag triggers a page reload when navigating to another page, always starting at the top.

Please note that I have tried all of the solutions mentioned above.

Answer №1

Within your page component, make sure to include the useEffect hook with the line window.scrollTo(0,0) in it.

useEffect(()=>{
  window.scrollTo(0,0);
},[])

Answer №2

Consider implementing scrollRestoration on a parent component.

 window.history.scrollRestoration = 'manual';

Answer №3

Utilize this particular hook and specify the ID as a dependency

useEffect(() => {
   window.scrollTo({
          top: 0,
          left: 0,
          behavior: "smooth"
        });
}, [id])

If you are using it in Next.js, ensure to include an if statement like this

useEffect(() => {

if(typeof window !== 'undefined'){
   window.scrollTo({
          top: 0,
          left: 0,
          behavior: "smooth"
        });
   }
}, [id])


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

Utilizing a singular component from Material UI

I'm in need of a Stepper component and the best option I came across was the MUI one. However, my app is built with react-bootstrap and I do not have MUI. I stumbled upon a post (Is it possible to install a package that contains only one component of ...

When utilizing CKEDITOR, the default TEXTAREA is obscured, and CKEDITOR does not appear

I am trying to incorporate CKEDITOR into my project. I have added the ckeditor script in the footer and replaced all instances of it. <script src="<?= site_url('theme/black/assets/plugins/ckeditor/ckeditor.min.js') ?>" type="text/javasc ...

Determine the radius using three given points

I am in need of determining the radius at the corners of a rectangle based on some given data points along the curve. The image below provides a visual representation: https://i.stack.imgur.com/7FHq0.png How can I calculate the radius using these specifi ...

Conceal a different div unless it includes

Hi everyone, I need help with a filter code snippet: $(".title").not(":contains('" + $("[name=filter]").val() + "')").hide() The issue I'm facing is that the .title class is nested within the .sortAll class along with many other divs. I w ...

Div with sidebar that sticks

I am currently working on setting up a website with a sticky sidebar. If you would like to see the page, click this link: On a specific subpage of the site, I am attempting to make an image Validator sticky, but unfortunately, it's not functioning a ...

The MUI classes in my React project differ between the local and live versions, creating inconsistency in styling

I've encountered a discrepancy in the Mui classes used in my React project between the local and live versions. For instance: Localhost MuiButtonBase-root MuiButton-root MuiButton-text MuiButton-textPrimary MuiButton-sizeSmall MuiButton-textSizeSmal ...

Change the date string to year, month, and day

When using Ajax's getResponseHeader("Last-Modified"), it returns a date string with the format displayed below: Thu Oct 13 2016 13:05:17 GMT+0200 (Paris, Madrid, sommartid) I am wondering if it is achievable in javascript to extract the year, month, ...

Using JavaScript to utilize a variable containing a .match method with Regex Expression

Recently, I started delving into the world of regex with the aim of incorporating variables in my matches. Imagine I have a string that reads "Total: $168" My goal is to extract just the numerical value; 168. This is what I currently have: totalCost = t ...

JavaScript code that opens a URL in a new tab with proper formatting

I'm having trouble figuring out how to make my JavaScript open a URL in a new tab. Here is the script: function viewSource(){ var webcache = "http://webcache.googleusercontent.com/search?q=cache:"; var request = "&prmd=ivn&strip=0& ...

How can you retrieve a value from a JavaScript closure function?

I'm struggling with getting a value from a closure function in Javascript. In my initial attempt, I placed the return statement inside the inner function, but it was not effective. Then, I tried moving the return statement to the outer function, howev ...

Replicate the functionality of a mouse scrolling event

I have incorporated Jack Moore's Wheelzoom jQuery plugin to zoom and drag an SVG image on my website. However, I also want to include manual zoom in and out buttons for the users. I am considering two options to achieve this - triggering a mouse whe ...

What is the method for invoking a function with arguments within an HTML `<p>` element?

I am looking to display like and dislike percentages on cards. <v-card v-if="software[2] == searched || searched == ''" class="software-card" > <h3>{{ software[2] }}</h3> ...

Wrapper class for iOS and Android libraries in React-Native

Currently, I am exploring React Native and aiming to develop a unified interface (wrapper) for two libraries with similar functionalities but tailored for different platforms. For instance, DatePickerIOS & react-native-wheel-picker-android. I've expe ...

What is the most efficient method for sending query parameters through a URL in Vue.js with Axios?

My goal is to use Axios upon page load to retrieve a JSON object from the base URL. When a button is clicked, I want to append query parameters to the URL and fetch a different JSON object. For example, if the base URL is 'test.com', clicking the ...

Tracking code execution in React, Enzyme, and Istanbul reveals uncovered functions running during tests

I have been working on testing a React component that involves 3 functions. The tests I've written for these functions pass successfully, but my code coverage report indicates only a 33% coverage. Here is the code snippet of the component: const AddW ...

Nginx Docker Configuration

After successfully building a React SPA, I configured my packer-main.json with the following settings: { "variables": { "version": "{{ env `CI_PIPELINE_IID` }}" }, "builders": [{ "type": "docker", "image": "IMAGE NAME", ...

Unable to fetch next Docker container: docker-compose container is missing the specified container

I've encountered an issue with my docker-compose setup. My objective is to deploy a Next.js app using a docker-compose file. Here's the current configuration from my DockerFile: FROM node:18 WORKDIR /app COPY package.json yarn.lock ./ RUN yarn i ...

Updating contact list to a database table structure

Currently, my code displays the data in address books, but I would like it to be shown in a table instead. I attempted to use document.write to create the table, but I'm unsure how to populate the table with the data rather than the address book forma ...

Unexpected TypeError thrown by a simple react-cube-navigation demonstration

Looking to utilize the react-cube-navigation component, available here. Encountering a TypeError when attempting to run the provided example, React throws an error: TypeError: props.rotateY.to(function (x) { return "scale is not a function. ( ...

Guide on uploading images to a NodeJS server from an Angular 2+ application

I have a NodeJS rest-API that can handle both images and text content in the same function. Currently, I am using multer in my NodeJS server to manage image uploads along with text content. Below is an example code snippet showcasing how I am handling this ...