Navigate back to the home page in Next.js and automatically scroll to the previous position you were at on the page

I'm currently working on a next.js app and I'm trying to implement a "back to start" link with specific behavior:

  1. The user starts on the main page and scrolls down.
  2. When navigating to a subpage, they should find the "back to start" link.
  3. If the user clicks on "back to start", they should be redirected to the main page with the scroll position intact from when they left.

However, if the user enters the subpage directly via URL, the "back to start" button should simply take them to the main page at the top.

I've created a codesandbox example for reference.

Here's what I've attempted so far:

  • Using the next.js <Link> component. However, this redirects to the main page scrolled to the top.
  • Trying the scroll={false} property for the next.js <Link>. This maintains the current scroll position but doesn't restore the original position.
  • Utilizing next.js router.back(). This works in preserving the scroll position when returning to the main page, but not if the user accesses the subpage directly via URL.

Do you have any suggestions or perhaps a combination of these strategies to achieve the desired functionality?

Answer №1

If you're utilizing an app directory, consider giving next-scroll-restorer a shot.

This tool is perfect for managing scroll restoration specifically in Next.js projects.

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 global.css base is not properly implementing the Tailwind styles

My global.css file contains some styling: @tailwind base; @tailwind components; @tailwind utilities; @layer base { .body { @apply bg-[#141414] text-white; // This should change the body color, but it's not working } } @layer componen ...

Utilize NPM package exclusively for server-side rendering (SSR) within a Next.js application

I'm currently attempting to incorporate a private NPM module exclusively during the initial page load when rendering is taking place on the server. Despite using the code below, I am noticing that my package still appears in chunks in client.html when ...

Ensuring User Data is Current in the UI with Firebase Auth Callbacks

Below is the standard method for setting the user state to currentuser that is returned from onAuthStateChanged. I am looking for a useEffect hook that will be triggered whenever there is an update to the user's information. Unfortunately, I am unable ...

Issue encountered during creation of a polyline in Cesium

When attempting to create a polyline in my ReactJs app using the code below, I encountered an error message stating "DeveloperError: Expected value to be greater than or equal to 0.0125, the actual value was 0." Can someone shed some light on why this er ...

Images with spaces in their names are failing to load in React Native

I am currently trying to utilize an image within my react native application. At this point, my code is very minimal. The following code snippet is all I have for now: import React from 'react'; import { ScrollView, View, Text } from 'reac ...

Encountering a favicon issue in Next.js 14 after restructuring the project to implement Internationalization

Having trouble with favicon display in Next.js 14.0.2. The issue cropped up after implementing internalization and reconfiguring my project structure. Here is a simplified view of my project structure: - app - [lang] - _components - _dictionaries ...

Guide to integrating Google Maps JS API into a React application without relying on third-party libraries

I'm currently grappling with the concept of integrating external APIs in React and am interested in using Google Maps' API to showcase a map within a child component. My goal is to gain insight into how this can be done without relying on any ext ...

Troubles encountered with adapting apexcharts size within a react environment

As a novice front-end coder transitioning from a data analyst background, I am currently facing an issue with integrating an ApexChart visual into a flexbox element. The visual appears fine at a resolution of 2560x1440 pixels. However, upon further resizin ...

Just dipping my toes into the world of backend development and diving into the intric

Hi everyone, I've been working on coding for a little over a year now and have mainly focused on frontend technologies like JavaScript, various frameworks, CSS, and HTML. Just yesterday, I encountered the notorious CORS issue with the Spotify API. Ev ...

react-relay Attempting to use @refetchable incorrectly within fragment definition

Currently, I am delving into learning react-relay (v13) and encountering an issue when trying to specify a pagination fragment with @refetchable. Despite having a straightforward structure, everything functions as intended without the usage of @refetchable ...

What can be done to ensure that two separate react-native Picker components do not interfere with each other's

Encountering an issue with two Pickers in a react-native View. Whenever I select a value in one Picker, it causes the other Picker to revert back to its initial item in the list. It seems like the onValueChange function is being triggered for both Pickers ...

What is the best way to calculate the overall number of comments per post when using node.js, react js, and sequelize?

Currently, I am working on a project that allows users to ask and answer questions. However, I am facing an issue with the comments field. The comments table displays data correctly and can delete entries, but I need to find a way to count the total number ...

Circular center button in the footer UI

Struggling with aligning a button in the footer perfectly? I have two icons on each side and while the UI is almost there, something seems off with the center icon's padding and shadow. I'm currently working with material-ui. Take a look at the i ...

Toggling between ascending and descending order on table header click in React

It seems like a simple task, but I am struggling to grasp the solutions I have come across. I currently have a function set up that changes the column order when I click on the header. However, I would like the second click to reverse the order. This is t ...

Using a customHook to dynamically swap images in React

Currently, I am facing an issue with a custom hook that manages the theme (dark/light mode) using tailwind CSS. Specifically, I have two images that are supposed to switch based on the theme mode selected. Despite successfully changing FontAwesome icons fr ...

Issue Confirming Signature - New Version of Next.JS with Stripe Integration

Having trouble verifying the request signature in my Stripe webhook endpoint. I keep encountering this error: No signatures found matching the expected signature for payload. Have you passed the raw request body received from Stripe? I've experimente ...

Hover your mouse cursor over the React Material UI TextField to see the icon

I am trying to customize the mouse cursor behavior of a TextField component from Material UI when its variant is set to "outlined". Currently, the cursor changes to Text but I want it to appear as a pointer instead. I attempted to override the default beha ...

Implementing material-ui autocomplete with search icon functionality

I am using the @material-ui autocomplete feature for search functionality, and I want to include a search icon next to the autocomplete component. I attempted to achieve this by adding the search icon, but the option fields are no longer displaying proper ...

Adding a new object to a nested array with MongoDB and Node.js

I'm struggling with pushing an object to a nested array, specifically in this Board document: { "boardMembers": [ "5f636a5c0d6fa84be48cc19d" ], "boardLists": [ { "cards": ...

Using the useContext hook in a TypeScript class component: a step-by-step guide

I am working with a TypeScript class component and have successfully created a context that can be accessed globally. I am interested in learning how to implement this context in a .ts class component and if it is possible to use it in a pure TypeScript ...