react-router-object

1.0.4 • Public • Published

react-router-object

Declarative object based routing for React Router

Codesandbox demo

NPM JavaScript Style Guide

Install

# yarn 
$ yarn add react-router-object
# npm 
$ npm install react-router-object

Usage

This is a basic routes configuration

import React from 'react'
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom'
import { applyPathToRoutesObj, mapRoutesObjToArray } from 'react-router-object'
import Page from './pages/Page'
 
const routesConfig = {
  // index is a reserved key for root paths
  index: {
    component: () => <Page title="Index" />,
    key: 'index',
    exact: true,
  },
  blog: {
    index: {
      component: () => <Page title="Blog" />,
      key: 'blog',
      exact: true,
    },
    author: {
      component: () => <Page title="Blog > Author" />,
      key: 'blog-author',
    },
  },
}
 
// add the path based on the position within the objects keys tree
const routesObj = applyPathToRoutesObj(routesConfig)
 
// convert the routes object into an array and that's it!
const routesArr = [...mapRoutesObjToArray(routesObj)]
 
const Routes = () => (
  <Router>
    <Switch>
      {routesArr.map(route => (
        <Route {...route} />
      ))}
    </Switch>
  </Router>
)
 
export default Routes

Provider

Using RoutesObjProvider you can easily access all, and current routes object.

Passes the routes prop containing:

Property Type Description
all object All routes
current object The current route

In your routes setup:

Important - RoutesObjProvider uses withRouter(), so make sure you place the provider inside the <Router>

import { RoutesObjProvider } from 'react-router-object'
 
const routesObj = applyPathToRoutesObj(routesConfig)
 
<Router>
  <RoutesObjProvider routes={routesObj}>
    <Switch>
      {routesArr.map(route => (
        <Route {...route} />
      ))}
    </Switch>
  </RoutesObjProvider>
</Router>

Wrap the consuming component with withRoutesObj and that's all!

import { withRoutesObj } from 'react-router-object'
 
const Page = props => {
  console.log(props.routes)
  return <h1>{props.title}</h1>
}
 
export default withRoutesObj(Page)

License

MIT © antoniojps

Readme

Keywords

none

Package Sidebar

Install

npm i react-router-object

Weekly Downloads

16

Version

1.0.4

License

MIT

Unpacked Size

135 kB

Total Files

6

Last publish

Collaborators

  • antoniojps