|
| 1 | +# React Router Async |
| 2 | +[](http://github.com/badges/stability-badges) |
| 3 | +[](https://www.npmjs.com/package/react-router-async) |
| 4 | +[](https://www.npmjs.com/package/react-router-async) |
| 5 | + |
| 6 | +``IMPORTANT NOTE! STATUS FOR THIS PROJECT IS EXPERIMENTAL AND THINGS CAN CHANGE, IT'S NOT READY FOR PRODUCTION`` |
| 7 | + |
| 8 | +React Router Async is ultimate routing solution for your React applications, especially it's good in universal applications. |
| 9 | + |
| 10 | +## Installation |
| 11 | +```bash |
| 12 | +yarn add react-router-async |
| 13 | +``` |
| 14 | + |
| 15 | +## Usage |
| 16 | +On client: |
| 17 | +```javascript |
| 18 | +import React from 'react'; |
| 19 | +import ReactDOM from 'react-dom'; |
| 20 | +import { Router } from 'react-router-async'; |
| 21 | +import { routes, hooks } from './common'; |
| 22 | +import createHistory from 'history/createBrowserHistory'; |
| 23 | + |
| 24 | +const history = createHistory(); |
| 25 | +const mountNode = document.getElementById('app'); |
| 26 | + |
| 27 | +Router.init({ path: history.location.pathname, routes, hooks }).then(({ Router, Component, router, callback }) => { |
| 28 | + ReactDOM.render(<Router {...{ Component, router, history }} />, mountNode, callback); |
| 29 | +}).catch(error => console.log(error)); |
| 30 | +``` |
| 31 | + |
| 32 | +On server (for example as express middleware): |
| 33 | +```javascript |
| 34 | +export default function (req, res, next) { |
| 35 | + Router.init({ path: req.path, routes, hooks }).then(({ Component, status, redirect }) => { |
| 36 | + if (redirect) { |
| 37 | + res.redirect(status, redirect); |
| 38 | + } else { |
| 39 | + const html = ReactDOM.renderToStaticMarkup(HtmlComponent({ |
| 40 | + markup: ReactDOM.renderToString(<Component />), |
| 41 | + assets: assets |
| 42 | + })); |
| 43 | + res.status(status).send('<!DOCTYPE html>' + html); |
| 44 | + } |
| 45 | + }).catch(error => { |
| 46 | + if (error.name === 'RouterError') { |
| 47 | + res.status(error.code).send(error.message); |
| 48 | + } else { |
| 49 | + res.status(500).send('Internal error'); |
| 50 | + } |
| 51 | + }); |
| 52 | +} |
| 53 | +``` |
| 54 | + |
0 commit comments