1.0.4 • Published 6 years ago
react-router-object v1.0.4
react-router-object
Declarative object based routing for React Router
Install
# yarn
$ yarn add react-router-object
# npm
$ npm install react-router-objectUsage
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 RoutesProvider
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