react-router-async
TypeScript icon, indicating that this package has built-in type declarations

0.7.11 • Public • Published

React Router Async

Latest Stable Version License

IMPORTANT NOTE! STATUS FOR THIS PROJECT IS EXPERIMENTAL AND THINGS CAN CHANGE, IT'S NOT READY FOR PRODUCTION

React Router Async is ultimate routing solution for your React applications, especially it's good in universal applications.

logo

Installation

yarn add react-router-async

Usage

On client:

import React from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter } from 'react-router-async';
import { routes, hooks } from './common';
import createHistory from 'history/createBrowserHistory';
 
const history = createHistory();
const mountNode = document.getElementById('app');
 
BrowserRouter.init({ path: history.location.pathname, routes, hooks, history }).then(({ Router, routerProps, Component, componentProps, callback }) => {
    ReactDOM.render(<Router {...routerProps} />, mountNode, callback);
}).catch(error => console.log(error));

On server (for example as express middleware):

export default function (req, res, next) {
    ServerRouter.init({ path: req.path, routes, hooks }).then(({ Router, routerProps, status, redirect }) => {
        if (redirect) {
            res.redirect(status, redirect);
        } else {
            const html = ReactDOM.renderToStaticMarkup(HtmlComponent({
                markup: ReactDOM.renderToString(<Router {...routerProps} />),
                assets: assets
            }));
            res.status(status).send('<!DOCTYPE html>' + html);
        }
    }).catch(error => {
        if (error.name === 'RouterError') {
            res.status(error.code).send(error.message);
        } else {
            res.status(500).send('Internal error');
        }
    });
}

Readme

Keywords

none

Package Sidebar

Install

npm i react-router-async

Weekly Downloads

34

Version

0.7.11

License

MIT

Unpacked Size

77.4 kB

Total Files

40

Last publish

Collaborators

  • olegman