Sign Up for Free

RunKit +

Try any Node.js package right in your browser

This is a playground to test code. It runs a full Node.js environment and already has all of npm’s 400,000 packages pre-installed, including found-scroll with all npm packages installed. Try it out:

require("found/package.json"); // found is a peer dependency. require("react/package.json"); // react is a peer dependency. var foundScroll = require("found-scroll")

This service is provided by RunKit and is not affiliated with npm, Inc or the package authors.

found-scroll v0.1.6

Scroll management for found

Found Scroll npm

Scroll management for Found.

Usage

import { createBrowserRouter, createRender } from 'found';
import { ScrollManager } from 'found-scroll';

/* ... */

const render = createRender({ renderError });

const BrowserRouter = createBrowserRouter({
  routeConfig,

  render: renderArgs => (
    <ScrollManager renderArgs={renderArgs}>
      {render(renderArgs)}
    </ScrollManager>
  ),
});

Guide

Installation

$ npm i -S react found
$ npm i -S found-scroll

Basic usage

When constructing a router, in the render method, wrap the rendered element with <ScrollManager>, and pass in renderArgs as a prop, as in the above example.

Custom scroll behavior

You can provide a custom shouldUpdateScroll callback as a prop to <ScrollManager>. This callback receives the previous and the current renderArgs.

The callback can return:

  • a falsy value to suppress updating the scroll position
  • a position array of x and y, such as [0, 100], to scroll to that position
  • a string with the id or name of an element, to scroll to that element
  • a truthy value to emulate the browser default scroll behavior
const shouldUpdateScrollByPathname = (prevRenderArgs, { location }) => (
  !prevRenderArgs || location.pathname !== prevRenderArgs.location.pathname
);

const shouldUpdateScrollByRoute = (prevRenderArgs, { routes }) => {
  if (routes.some(route => route.ignoreScrollBehavior)) {
    return false;
  }

  if (routes.some(route => route.scrollToTop)) {
    return [0, 0];
  }

  return true;
};

const render = renderArgs => (
  <ScrollManager
    shouldUpdateScroll={shouldUpdateScrollByPathname}
    renderArgs={renderArgs}
  >
    {/* ... */}
  </ScrollManager>
);

You can customize <ScrollManager> even further by providing a createScrollBehavior callback that creates the scroll behavior object. This allows using a custom subclass of ScrollBehavior from scroll-behavior with custom logic. When using a custom createScrollBehavior callback, you can continue to specify the shouldUpdateScroll callback as above.

const render = renderArgs => (
  <ScrollManager
    createScrollBehavior={config => new MyScrollBehavior(config)}
    renderArgs={renderArgs}
  >
    {/* ... */}
  </ScrollManager>
);
RunKit is a free, in-browser JavaScript dev environment for prototyping Node.js code, with every npm package installed. Sign up to share your code.
Sign Up for Free