• Stars
    star
    105
  • Rank 328,135 (Top 7 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created over 4 years ago
  • Updated over 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

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

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.

More Repositories

1

node-cross-spawn

A cross platform solution to node's spawn and spawnSync
JavaScript
1,067
star
2

next-layout

Add persistent and nested layouts to your Next.js projects in a declarative way
JavaScript
257
star
3

node-proper-lockfile

An inter-process and inter-machine lockfile utility that works on a local or network file system.
JavaScript
221
star
4

node-promptly

Simple command line prompting utility for nodejs
JavaScript
148
star
5

gatsby-plugin-ipfs

Adds support for deploying Gatsby to IPFS by ensuring that assets are relative
JavaScript
113
star
6

next-with-moxy

MOXY's boilerplate to accelerate the setup of new Next.js based web applications
JavaScript
101
star
7

js-proper-url-join

Like path.join but for a URL
JavaScript
40
star
8

next-intl

Library to integrate react-intl with Next.js.
JavaScript
40
star
9

webpack-isomorphic-dev-middleware

The webpack-dev-middleware, but for isomorphic applications
JavaScript
39
star
10

react-with-moxy

MOXY's boilerplate to create isomorphic react applications
JavaScript
36
star
11

js-deep-for-each

Recursively iterates over collections arrays and objects
JavaScript
35
star
12

node-token-dealer

Circumvent API rate limits by having several API tokens and let the dealer manage and give them to you
JavaScript
24
star
13

react-native-with-moxy

MOXY's boilerplate to accelerate the setup of new React Native mobile apps
JavaScript
22
star
14

js-class-is

Enhances a JavaScript class by adding an is<Class> property to compare types between realms.
JavaScript
17
star
15

webpack-isomorphic-compiler

A compiler that makes your life easier if you are building isomorphic webpack powered apps, that is, single page applications with server-side rendering
JavaScript
16
star
16

react-page-swapper

An orchestrator that eases out the implementation of page transitions
JavaScript
15
star
17

eslint-config

MOXY eslint configuration to be used across several JavaScript projects
JavaScript
14
star
18

react-carousel

A React carousel component that aims to be as flexible as possible
JavaScript
14
star
19

react-contentful-image

A react image renderer that uses the Contentful Images API.
JavaScript
12
star
20

ugo

An extensible and composable cli
12
star
21

next-sitemaps

An API handler and a plugin that enables your Next.js application to have working sitemaps
JavaScript
12
star
22

js-keyboard-only-outlines

Disable outlines caused by navigation methods other than keyboard
JavaScript
11
star
23

next-common-files

Next.js plugins that configure webpack with loaders for common files
JavaScript
9
star
24

react-promiseful

A React component and hook to render children conditionally based on a promise state
JavaScript
9
star
25

postcss-preset

PostCSS preset to be used at MOXY
JavaScript
8
star
26

next-env

Next.js plugin to pass environment variables to Next.js's configuration
JavaScript
8
star
27

webpack-sane-compiler

A webpack compiler wrapper that provides a nicer API
JavaScript
8
star
28

react-lib-template

This template aims to make the implementation of react component packages easier and more methodic.
JavaScript
8
star
29

stylelint-config

MOXY stylelint configuration to be used across several CSS projects
JavaScript
8
star
30

next-pre-compression

Next.js plugin to compress static assets at build time and serve them instead of having to compress on-the-fly
JavaScript
8
star
31

node-gh-issues-stats

Collect statistical information about issues of a GitHub repository
JavaScript
8
star
32

next-link

A component that enables client-side transitions between routes as well as external URLs.
JavaScript
7
star
33

redux-mock-store-await-actions

Waits for specific actions to be dispatched or a timeout expires
JavaScript
7
star
34

webpack-isomorphic-compiler-reporter

Beautiful reporting for webpack-isomorphic-compiler compilation events
JavaScript
7
star
35

react-split-text

A react component that wraps each word of a sentence into a <span> element.
JavaScript
6
star
36

yargs-get-help

Get the help output from a yargs instance
JavaScript
6
star
37

js-chained-config

Use a chaining API to generate and simplify the modification of configs
JavaScript
5
star
38

workshop-react

A workshop to introduce developers to React, presented in the Aveiro University
JavaScript
5
star
39

babel-preset

Babel preset to be used at MOXY
JavaScript
5
star
40

yargs-unparser

Converts back a yargs argv object to its original array form
5
star
41

next-compile-node-modules

Next.js plugin to compile all node_modules using Babel
JavaScript
5
star
42

yargs-promise-handler

Adds support for promises to yargs handlers and allows them to be composable
JavaScript
5
star
43

react-wait-for-react

Easily render a splash screen and loader while your React app is not yet interactive, optionally waiting for a promise as well
JavaScript
5
star
44

react-app-rewire-css-modules-extensionless

Enables CSS modules without any special extension for CRA apps using react-app-rewired
JavaScript
5
star
45

react-keyboard-only-outlines

Disable outlines caused by navigation methods other than keyboard
JavaScript
4
star
46

webpack-sane-compiler-notifier

Notify webpack compilation status to your operating system when using webpack-sane-compiler
JavaScript
4
star
47

react-icon

A component to render svg icons.
JavaScript
4
star
48

next-rest-api

Aims to ease the development of REST APIs in Next.js
JavaScript
4
star
49

next-seo

Manage document head SEO metadata in your Next.js projects with a simple data structure.
JavaScript
4
star
50

node-fetch-coverage

Fetch the code coverage from an open-source GIT repository, using a variety of well-known coverage services
JavaScript
4
star
51

webpack-sane-compiler-reporter

Beautiful reporting for webpack-sane-compiler compilation events
JavaScript
4
star
52

react-modal

A modal, built on top of react-modal, that also fixes the scrollable body in iOS
JavaScript
3
star
53

node-is-regular-file

Checks if a path is a regular file
JavaScript
3
star
54

react-navigation

Set of react components, hooks and providers to easily kickoff a navigation environment in web projects.
JavaScript
3
star
55

webpack-isomorphic-compiler-notifier

Notify webpack compilation status to your operating system when using webpack-isomorphic-compiler
JavaScript
3
star
56

js-pico-signals

A very simple signal library inspired by the 'signals' package
JavaScript
3
star
57

react-svg

MOXY'S base SVG component.
JavaScript
3
star
58

next-button

A react button that doubles down as a link.
JavaScript
3
star
59

jest-config

MOXY's Jest configuration to be used across several JavaScript projects
JavaScript
3
star
60

react-contentful-rich-text

A react component that transforms a contentful rich text structure to html.
JavaScript
3
star
61

react-animate-text

A react component that animates text per word and/or per line.
JavaScript
2
star
62

react-with-moxy-scripts

This package includes scripts and configuration used by react-with-moxy
2
star
63

create-next-routes

A CLI to manage Next.js routes
JavaScript
2
star
64

react-redata

React data container for isomorphic applications, providing a unified and performant load & reload pattern
JavaScript
2
star
65

react-circle

MOXY's circle animation component
JavaScript
2
star
66

next-webpack-oneof

Wraps all webpack loader rules into a single oneOf rule
JavaScript
2
star
67

rfcs-oss

RFCs for additions or changes to MOXY open-source projects
2
star
68

workshop-leveling-up-with-redux

Redux workshop composed by an introductory section, followed by some advanced aspects.
JavaScript
2
star
69

react-ellipsis

Moxy's base Ellipsis component.
JavaScript
1
star
70

react-app-rewire-external-svg-loader

Enables external-svg-loader for CRA apps using react-app-rewired
JavaScript
1
star
71

react-accordion

MOXY's base Accordion component.
JavaScript
1
star
72

next-with-router-ref

An alternative to Next.js withRouter HOC that supports refs by forwarding them
JavaScript
1
star
73

react-dropdown

A Dropdown component for React, based on react-select.
JavaScript
1
star
74

express-ensure-content-type

Express middleware that ensures requests match the specified content-type.
JavaScript
1
star
75

workshop-the-hitchhikers-guide-to-react

React workshop composed by an introductory section, followed by some advanced aspects.
JavaScript
1
star
76

redux-await-actions

Waits for specific actions to be dispatched or a timeout expires.
JavaScript
1
star