npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@moxy/next-router-scroll

v2.2.0

Published

Take control of when scroll is updated and restored in your Next.js projects

Downloads

1,553

Readme

next-router-scroll

NPM version Downloads Build Status Coverage Status Dependency status Dev Dependency status

Take control of when scroll is updated and restored in your Next.js projects.

Installation

$ npm install @moxy/next-router-scroll

This library is written in modern JavaScript and is published in both CommonJS and ES module transpiled variants. If you target older browsers please make sure to transpile accordingly.

Motivation

There are some cases where you need to take control on how your application scroll is handled; namely, you may want to restore scroll when user is navigating within your application pages, but you need to do extra work before or after the page has changed, either by using some sort of page transition or any other feature.

@moxy/next-router-scroll makes it easy to update the window scroll position just like a browser would, but programmatically.

This package is built on top of scroll-behavior and it's meant to be used in Next.js applications. It actively listens to Next.js router events, writing the scroll values associated with the current location in the Session Storage and reading these values whenever updateScroll() is called.

Usage

First install the provider in your app:

// pages/_app.js
import { RouterScrollProvider } from '@moxy/next-router-scroll';

const App = ({ Component, pageProps }) => (
    <RouterScrollProvider>
        <Component { ...pageProps } />
    </RouterScrollProvider>
);

export default App;

Then use the hook or HOC to update the scroll whenever you see fit.

// pages/index.js
import { useRouterScroll } from '@moxy/next-router-scroll';

const Home = () => {
    const { updateScroll } = useRouterScroll();

    useEffect(() => {
        updateScroll();
    }, []);
};

export default Home;

⚠️ By default, <RouterScrollProvider /> monkey patches Next.js <Link /> component, changing the scroll prop default value to false. You can disable this behavior by setting the disableNextLinkScroll prop to false.

API

<RouterScrollProvider />

A provider that should be used in your app component.

shouldUpdateScroll?

Type: function

A function to determine if scroll should be updated or not.

// pages/_app.js
import { RouterScrollProvider } from '@moxy/next-router-scroll';

const App = ({ Component, pageProps }) => {
    const shouldUpdateScroll = useMemo((prevContext, context) => {
        // Both arguments have the following shape:
        // {
        //     location,
        //     router: { pathname, asPath, query }
        // }
    }, []);

    return (
        <RouterScrollProvider shouldUpdateScroll={ shouldUpdateScroll }>
            <Component { ...pageProps } />
        </RouterScrollProvider>
    );
};

export default App;

Check custom scroll behavior for more information.

⚠️ Please note that prevContext might be null on the first run.

disableNextLinkScroll?

Type: boolean
Default: true

True to set Next.js Link default scroll property to false, false otherwise. Since the goal of this package is to manually control the scroll, you don't want Next.js default behavior of scrolling to top when clicking links.

children

Type: ReactNode

Any React node to render.

useRouterScroll()

A hook that returns an object with the following shape:

{
    updateScroll(prevContext?, context?),
    registerElement(key, element, shouldUpdateScroll?, context?),
    unregisterElement(key)
}

updateScroll(prevContext?, context?)

Call updateScroll function whenever you want to update the scroll. You may optionally pass prevContext and context objects which will be available inside shouldUpdateScroll.

Please note that prevContext and context have default values and any values you pass will be mixed with the default ones.

Use With Async Rendering:

If you're asyncronously loading DOM elements and need to wait for an element you can utilize React's approach for measuring DOM nodes. Here is an example of what that could look like:

const MyComponent = () => {
    const { updateScroll } = useRouterScroll();
    const divRef = useCallback((node) => {
        if (node) {
            updateScroll();
        }
    }, [updateScroll]);


    return someCondition ? <div ref={ divRef }>hi</div> : null;
};

registerElement(key, element, shouldUpdateScroll?, context?)

Call registerElement method to register an element other than window to have managed scroll behavior. Each of these elements needs to be given a unique key at registration time, and can be given an optional shouldUpdateScroll callback that behaves as above. This method can optionally be called with the current context if applicable, to set up the element's initial scroll position.

unregisterElement(key)

Call unregisterElement to unregister a previously registered element, identified by key.

withRouterScroll(Component)

A HOC that injects a routerScroll prop, with the same value as the hook variant.

import { withRouterScroll } from '@moxy/next-router-scroll';

const MyComponent = ({ routerScroll }) => {
    // ...
};

export default withRouterScroll(MyComponent);

Tests

$ npm test
$ npm test -- --watch # during development

Demo

A demo project is available in the /demo folder so you can try out this component.

First, build the next-router-scroll project with:

$ npm run build

Note: Every time a change is made to the package a rebuild is required to reflect those changes on the demo. While developing, it may be a good idea to run the dev script, so you won't need to manually run the build after every change

$ npm run dev

To run the demo, do the following inside the demo's folder:

$ npm i
$ npm run dev

License

Released under the MIT License.