react-routing-library v0.17.0
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
License
MIT License, Copyright © 2020 James K. Nelson