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

array-router

v0.9.2

Published

Lightweight, minimalist router for React

Downloads

9

Readme

Array-router ci nycrc config on GitHub

Array-route is a simple, light-weight library that helps you manage routes in your React application. It's designed for React 18 and above.

Installation

npm install --save-dev array-router

Syntax

App.js

import { useRouter } from 'array-router';
/* ... */
export default function App() {
  const provide = useRouter();
  return (
    <div className="App">
      {provide((parts, query, { throw404 }) => {
        try {
          switch (parts[0]) {
            case undefined:
              return <WelcomePage />
            case 'categories':
              return <CategoryPage />
            case 'forums':
              return <ForumPage />
            default:
              throw404();
          }
        } catch (err) {
          return <ErrorPage error={err} />
        }
      })}
    </div>
  );
}

CategoryPage.js

export default function CategoryPage() {
  const [ parts, query ] = useRoute();
  const categoryId = parts[1];
  return (
    /* ... */
  );
}

Basic design

Array-router does not actually provide any routing logic. Instead, it gives you an Array containing pathname.split('/') and an Object containing values from searchParams. You can then use them to build out a routing scheme that suits the needs of your app.

The aforementioned array and object are JavaScript proxy objects. Array-router tracks all actions you perform on them and takes appropriate actions based on this information. In the above example, Array-router knows that App reads the first item when it renders while CategoryPage reads the second. If the location changes from /categories/1 to /categories/2, Array-router will ask CategoryPage to rerender but not App since only parts[1] is different.

Mutation of parts or query will cause the location to change. For instance, parts.push('product', 17) would move you from /categories/1 to /categories/1/product/17. Conversely, parts.pop() would send you from /categories/1 to /categories while parts.splice(0) would send you all the way back to the root level.

Override default push vs. replace behavior

By default, changes to parts trigger calls to history.pushState while changes to query trigger calls to history.replaceState. When both type of changes occur, pushState has precedence.

You can use replacing to indicate that changes to the path should trigger a replaceState instead of the default pushState:

  replacing(() => {
    parts[0] = 'categories';
    parts[1] = 17;
  });

Conversely, you can use pushing to force the use of pushState when query variables are changes:

  pushing(() => query.search = evt.target.value);

Changing route during rendering

Normally, you would change parts or query inside event handlers. You can make changes while a component is rendering--if you must. To do so, you need to use replacing:

function ProjectPage() {
  const [ parts, query, { replacing } ] = useRoute();
  if (parts[1] === 'summary') {
    // fix an outdated URL
    replacing(() => parts[1] = 'overview');
  }
  /* ... */
}

replacing will throw a RouteChangeInterruption error. When the router receives this error from its error boundary, the changes will get applied. The error boundary's subsequent attempt at reconstructing the component tree should then proceed without incident.

This behavior is applicable to consumers of useRoute only. At the root level, changes get applied immediately.

Error handling

Array-router provides an error boundary that redirect errors to the root-level component (i.e. the one that calls useRouter). A captured error is rethrown the moment your code attempts to access one of the proxies (parts or query) or when rethrow is called.

Array proxy

Working with array elements is somewhat unintuitive. parts[0], parts[1] don't tell us what they actually represent. This is why the library provides a way for you to reference array elements by name instead:

  const route = arrayProxy(parts, {
    screen: 0,
    id: 1,
  });
  if (route.screen === 'products') {
    if (route.id) {
      return <ProductPage id={route.id} />;
    } else {
      return <ProductList />;
    }
  } else ...

route.screen in the example is mapped to parts[0] while route.id is mapped parts[1]. The mapping works for both reading and writing. It works for deleting too: delete route.screen; is translated as parts.splice(0) (since removal of both the zeroth element and those coming after is the only way we can ensure that parts[0] would yield undefined).

See the documentation of arrayProxy for more sophisticated ways of mapping elements to properties.

Usage in non-web environment

This library can be employed in a non-web environment. You need to provide the following functions for handling URLs in the router options:

API Reference

Hooks

Router methods

Error objects

Compatibility

Array-router makes use of JavaScript proxy. According to Mozilla, it is available in the following environment:

Proxy compatibility

Since the functionality in question cannot be polyfilled, Array-router does not work in any version of Internet Explorer or Opera Mini.