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

rax-use-router

v3.1.2

Published

Rax useRouter hook.

Downloads

260

Readme

rax-use-router

Rax hooks for router.

Install

npm i rax-use-router --save

Example

Use useRouter to config routing rules, each route map to a component. All route props (location and history) are available to User.

import { createElement, Fragment } from 'rax';
import { useRouter } from 'rax-use-router';
import { createHashHistory } from 'history';
import Foo from './Foo';
import NotFound from './NotFound';

const config = () => {
  return {
    history: createHashHistory(),
    routes: [
      // Static Component
      {
        path: '',
        component: <>
          <h1>Hello</h1>
        </>,
      },
      {
        path: '/home',
        routes: [
          // Dynamic Component 
          {
            path: '',                  // www.example.com/home
            component: (props) => {
              return (
                <>
                  <button onClick={() => props.history.push('/foo')}>go foo</button>
                  <button onClick={() => props.history.push('/bar')}>go bar</button>
                  <button onClick={() => props.history.push('/home/jack')}>go jack</button>
                </>
              )
            },
          },
          // URL Parameters
           {
            path: '/:username',        // www.example.com/home/xxx
            component: (props) => {
              return (
                <>
                  <p>{props.username}</p>
                  <button onClick={() => props.history.push('/home')}>Go home</button>
                </>
              )
            }
          }
        ]
      },
      // Code Splitting
      {
        path: '/bar',
        routes: [
          {
            path: '',                 // www.example.com/bar
            component: () => import(/* webpackChunkName: "bar" */ './Bar').then((Bar) => {
              // interop-require see: https://www.npmjs.com/package/interop-require
              Bar = Bar.__esModule ? Bar.default : Bar;
              // return a created element
              return <Bar />;
            }),
          },
        ],
      },
      {
        path: '/foo',                 // www.example.com/foo
        component: () => <Foo />,  
      },
      // No match (404)
      {
        component: () => <NotFound />,
      }
    ]
  }
};

export default function Example() {
  const { component } = useRouter(config);
  return component;
}
// Foo.jsx
import { createElement } from 'rax';
import { withRouter } from 'rax-use-router';

function Foo(props) {
  return <button onClick={ () => props.history.push('/home') }>Go home</button>
}
export default withRouter(Foo);
// Bar.jsx
import { createElement } from 'rax';
import { withRouter } from 'rax-use-router';

function Bar(props) {
  return <button onClick={ () => props.history.push('/home') }>Go home</button>
}
export default withRouter(Bar);
// NotFound.jsx
import { createElement } from 'rax';
import { withRouter } from 'rax-use-router';

function NotFound(props) {
  return <button onClick={ () => props.history.replace('/home') }>Go home</button>
}
export default withRouter(NotFound);

API Reference

useRouter({ history, routes })

history

history provides 3 different methods for creating a history object, depending on your environment.

  • createBrowserHistory is for use in modern web browsers that support the HTML5 history API (see cross-browser compatibility)
  • createMemoryHistory is used as a reference implementation and may also be used in non-DOM environments, like React Native or tests
  • createHashHistory is for use in legacy web browsers

routes

Route options:

path

Any valid URL path or array of paths that path-to-regexp@^1.7.0 understands.

{
  path: '/users/:id',
  component: () => <User />,  
}

When doesn’t match any of routes, if there a route without a path will match that rule, just like a 404.

{
  component: () => <NotFound />,  
}
component

A component to render when the location matches.

{
  path: '/:username',        // www.example.com/home/xxx
  component: (props) => {
    return (
      <>
        <p>{props.username}</p>
        <button onClick={() => props.history.push('/home')}>Go home</button>
      </>
    )
  }
}
exact

Default true, when false, will not match if the path matches the location.pathname exactly.

{
  path: '/foo',
  exact: false,
  component: () => <Foo />,  
}

| path | location.pathname | exact | matches? | | ------ | ----------------- | ------- | -------- | | /foo | /foo/bar | true | no | | /foo | /foo/bar | false | yes |

strict

Default false, when true, a path that has a trailing slash will only match a location.pathname with a trailing slash. This has no effect when there are additional URL segments in the location.pathname.

{
  path: '/foo',
  strict: true,
  component: () => <Foo />,
}

| path | location.pathname | matches? | | ------- | ----------------- | -------- | | /foo/ | /foo | no | | /foo/ | /foo/ | yes | | /foo/ | /foo/bar | yes |

Warning: strict can be used to enforce that a location.pathname has no trailing slash, but in order to do this both strict and exact must be true.

{
  path: '/foo',
  exact: true,
  strict: true,
  component: () => <Foo />,
}

| path | location.pathname | matches? | | ------ | ----------------- | -------- | | /foo | /foo | yes | | /foo | /foo/ | no | | /foo | /foo/bar | no |

sensitive

Default false, when true, will match if the path is case sensitive.

{
  path: '/foo',
  sensitive: ture,
  component: () => <Foo />,  
}

| path | location.pathname | sensitive | matches? | | ------ | ----------------- | --------- | -------- | | /foo | /foo | true | yes | | /foo | /Foo | false | yes | | /Foo | /foo | true | no | | /foo | /Foo | true | no |

withRouter(Componet)

withRouter will pass updated location, and history props to the wrapped component whenever it renders.

// Foo.jsx
import { createElement } from 'rax';
import { withRouter } from 'rax-use-router';

function Foo(props) {
  const {history, location} = props;
  return <button onClick={ () => history.push('/home') }>{location.pathname}</button>
}
export default withRouter(Foo);

history

Each history object has the following properties:

  • history.length - The number of entries in the history stack.
  • history.location - The current location (see below).
  • history.action - The current navigation action, such as push, replace, go and so on.

For more information, see history

location

The location object implements a subset of the window.location interface, including:

  • location.pathname - The path of the URL
  • location.search - The URL query string
  • location.hash - The URL hash fragment

For more information, see history

Notice

In most cases, we don't recommend using useRouter in multiple places on the page. Reason of this is the latter routerConfig will override the previous.