react-router-resolver
Were you thinking about how to load data before transition or how to load it on server-side with using react-router v4? Or maybe you thought how to load chunks before transition by click the link? What about security system on your project ? Alright, you can talk that there are too many library what implements it... But I can suggest the powerful and small sized library what can help to do it on client-side and for server-side too
Alright, let's start
Contents
Internal dependencies:
package | ver |
---|---|
is-browser | ^2.0.1 |
qs | 6.5.1 |
react-display-name | ^0.2.3 |
shallowequal | ^1.0.2 |
External dependencies:
package | ver |
---|---|
react-router | ^4.2.0 |
react-router-config | 1.0.0-beta.4 |
Simple example
if you didn't work with the react-router-config
please follow the link and review
./src/routes/index.js
const App = <div> <ul> <li> <NavLink to='/'>to home</Link> </li> <li> <NavLink to='/test'>to test page</Link> </li> </ul> </div> const Test = 'I am test page' path: '/' component: App routes: path: '/test' component: Test
Ok, this is just example. let's try to add react-router-resolver to do with
We need to load data before transition to /test
. Ok
path: '/' component: App routes: path: '/test' component: Test preload: async { // preload will wait and hold the transition until the promise is resolved or rejected // here is we can to load data and put it to your storage like redux/mobx/mobx-state-tree and others... helpers }
Example usage with redux
./src/resolver.js
let resolver const getResolver = { if resolver return resolver resolver = routes store history actions: store store store helpers: store history dispatch: storedispatch getState: storegetState // here is you can put your own helpers ... resolved: return resolver}
./src/App.jsx
const App = async { const resolver = try await resolver catch e console return <Provider store=store> <ConnectedRouter history=history> </ConnectedRouter> </Provider> }
./src/index.js
const history = const store = const render = { } if modulehot modulehotaccept'./App'
And test it :)
API
method | desctiption |
---|---|
getRoutes | returns array of passed routes to the resolver |
getResolved | returns an array of all resolved routes |
setHelpers | (helpers) setting helpers for preload/onEnter hooks |
addHelper | (key, value) add helper |
resolve | (location) resolve routes for server-side |
init | (location) resolve routes for client-side |
Helpers
const preloadOptions = // this is default options alwaysReload: false reloadOnParamsChange: true reloadOnQueryChange: true // also you can use decorators style@@@Component { const data = thisprops return // use data in your component }
onEnter like preload but onEnter fires always when location is change
or like object
path: '/test' component: Test preload: async { const data = await helpers } preloadOptions: // this is default options alwaysReload: false reloadOnParamsChange: true reloadOnQueryChange: true