How do I make scrolling update the history in next.js?

60 Views Asked by At

Quick note: this question is not seeking to scroll when a linked is clicked, and is not seeking to restore the scroll position when a link is clicked, but rather to add new items to the browser state when the page is scrolled

I am working on a codebase where I wish to update the history to new anchors when someone scrolls, eg:

<h1 id="one">
  <a href="#one">Link one</a>
</h1>

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Lobortis feugiat vivamus at augue eget arcu dictum. Pulvinar neque laoreet suspendisse interdum. Odio euismod lacinia at quis. Laoreet suspendisse interdum consectetur libero id faucibus nisl. 

<h1 id="two">
  <a href="#two">Link two</a>
</h1>

Lacus sed viverra tellus in hac habitasse platea. Aliquam etiam erat velit scelerisque in dictum non. Ut aliquam purus sit amet luctus venenatis lectus magna fringilla. At imperdiet dui accumsan sit amet. 

I am very familiar with JS itself, so history.pushState() and intersection observers are familiar to me, but I don't use React or Next very often anymore.

import Link from "next/link";
import { useRouter } from "next/router";

I also see there is a newer

import { useRouter } from 'next/navigation'

around which seems to replace the old router.

What is 'the NextJS way' to make the browser's URL update as the items appear in the view?

I have the next docs for the link component doesn't seem to cover this (only the unrelated concept of scrolling when a link is clicked). However the next docs for the link component uses this technique itself - scroll the page and watch the URL update - which seems to indicate a native Next.js solution already exists.

1

There are 1 best solutions below

0
Grisaia On

Current state of scroll restoration in Next.js leaves much to be desired.

All existing scroll restoration solution in Next.js are tricky and do not follow the real website behaviour. Is you are using app directory, give a try to next-scroll-restorer package. It relies on History API so the browser decides whether anchor is a new history state, or not. next-scroll-restorer tries to reproduction an old plain behaviour of html websites for a Single Page Applications.