react-routing-library
TypeScript icon, indicating that this package has built-in type declarations

0.17.0 • Public • Published

React Routing Library

**Simple, powerful routing that grows with your app.**

NPM

Getting Started

yarn add react-routing-library

2-minute primer

Your router just is a function.

With React Routing Library, a router is a function that maps a request to an element.

type Router = (request: RouterRequest) => ReactNode

You've seen this before -- its a lot like a React component.

const router = request => {
  switch (request.pathname) {
    case '/':
      return <h1>Home</h1>

    case '/about':
      return <h1>About</h1>

    default:
      throw new Error('Not Found')
  }
}

Once you have a router, just pass it to a <RoutingProvider>. Then, use a <Content /> element to indicate where you want your content to be rendered.

import { Content, RoutingProvider } from 'react-routing-library'

export default function App() {
  return (
    <RoutingProvider router={router}>
      <Content />
    </RoutingProvider>
  )
}

Routers-as-functions is the underlying secret that makes RRL so powerful. Most of the time though, it's easier to let RRL create router functions for you. For example, the above router could be created with createPatternRouter().

import { createPatternRouter } from 'react-routing-library'

const router = createPatternRouter({
  '/': <h1>Home</h1>,
  '/about': <h1>About</h1>
})

Naturally, your <Content> element can be nested anywhere inside the routing provider. This lets you easily add layout elements, for example a site-wide navigation bar. And hey presto -- you've now built a simple app with push-state routing!

View this example live at CodeSandbox »

import { Link } from 'react-routing-library'

function AppLayout({ children }) {
  return (
    <>
      <header>
        <Link to="/">Home</Link>
        <Link to="/about">About</Link>
      </header>
      <main>
        {children}
      </main>
    </>
  )
}

export default function App() {
  return (
    <RoutingProvider router={router}>
      <AppLayout>
        <Content />
      </AppLayout>
    </RoutingProvider>
  )
}

API

Components

Hooks

Router helpers

Functions

Error handling

Types

License

MIT License, Copyright © 2020 James K. Nelson

Package Sidebar

Install

npm i react-routing-library

Weekly Downloads

0

Version

0.17.0

License

MIT

Unpacked Size

121 MB

Total Files

686

Last publish

Collaborators

  • jamesknelson