1.0.4 • Published 5 years ago

react-router-object v1.0.4

Weekly downloads
3
License
MIT
Repository
github
Last release
5 years ago

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:

PropertyTypeDescription
allobjectAll routes
currentobjectThe 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

1.0.4

5 years ago

1.0.3

5 years ago

1.0.2

5 years ago

1.0.1

5 years ago

1.0.0

5 years ago