npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

koa-react-router

v4.0.0

Published

react-router middleware for koa 2.

Downloads

63

Readme

koa-react-router

koa 2 middleware for React server side rendering and routing with react-router 5.

Looking for React Router 3 support see v1 docs. Try React Router 5 though it's awesome!

Usage

To install koa-react-router:

  npm install koa-react-router react react-dom react-router --save

Note: react react-dom & react-router are all peerDependencies of koa-react-router.

koa-react-router can be mounted easily in a koa 2 application like so:

  // index.js
  import Koa from 'koa';
  import reactrouter from 'koa-react-router';
  import App from './App';
  import Container from './containers/PageContainer';

  const app = new Koa();

  app.use(reactrouter({
    App,
    onError: (ctx, err) => console.log('I Have failed!!!!'),
    onRedirect: (ctx, redirect) => console.log('I have redirected!'),
    onRender: (ctx) => ({ Container })
  }));

API

koa-react-router requires the following parameters:

App

The App config prop should be a react component that contains one or more React Router 4 Route components to be rendered. For example:

  // App.js
  import React from 'react';
  import { Route } from 'react-router';
  import Home from '../containers/Home';
  import Article from '../containers/Article';

 const App = () =>
    <div>
      <h1>This is my App!</h1>
      <Route path="/" component={Home} exact />
      <Route path="/article" component={Article} exact />
    </div>;

  // index.js
  // ...imports
  import App from './App';

  // ... koa app setup
  app.use(reactrouter({
    App,
    // Other callbacks
  }));  

preRender

Callback function called before rendering App. This callback can either be a normal function which returns a valid component or it can return a Promise which then resolves and returns a valid component. The function accepts the following parameters:

  • component - The StaticRouter wrapped around the App.

This callback could be used to wrap the component with any other higher-order component before it gets rendered

onError

Callback function called when an error occurs whilst route matching or rendering.
The function accepts the following parameters:

  • ctx - The Koa Context object.
  • err - The error that was caught when matching routes.

onRedirect

Callback function called if a Redirect route is matched.
The function accepts the following parameters:

  • ctx - The Koa Context object.
  • redirectUrl - The url to redirect to.

onRender

Callback function called before sending a response to the client. This function must be supplied, and must return an object that contains the following property:

Container

This should be a React component that wraps around the rendered route.
Typically this will be the template for the page, however this is not mandatory.
As such this component is rendered using renderToStaticMarkup.
The component must accept the children prop and insert it when rendered. For example:

  // ./containers/Container
  import React from 'react';

  const Container = (props) =>
    <html lang="en">
      <head>
        <title>Hello Container</title>
      </head>
      <body>
        <div id="app">
          {props.children}
        </div>
      </body>
    </html>;

  export default Container;

This would then be supplied to koa-react-router via the onRender callback like so:

  // index.js
  import Koa from 'koa';
  import reactrouter from 'koa-react-router';
  import App from './App';
  import Container from './containers/Container';

  const app = new Koa();

  app.use(reactrouter({
    App,
    onRender: (ctx) => ({ Container })
  }));

As well as the Container property this callback can optionally return:

containerRenderer

Optional function for handling the rendering of a container component.
This function has one argument which is view. This argument is the currently rendered view of the app.
This function may be used if some custom props need to be injected into the container component, such as an initial Redux state.
This function should be used instead of the Container property when returning from onRender.
For example you may want to render the container as follows:

  // index.js
  import Koa from 'koa';
  import reactrouter from 'koa-react-router';
  // ...other imports

  const app = new Koa();

  const state = // Create state.

  app.use(reactrouter({
    App,
    onRender: (ctx) => ({
      containerRenderer: (view) =>
      <html lang="en">
        <head>
          <script dangerouslySetInnerHTML={{ __html: state}} />
        </head>
        <body>
          <p>hello container</p>
          <div dangerouslySetInnerHTML={{ __html: view }} />
        </body>
      </html>
    })
  }));

The final page render would look something like:

<html lang="en">
  <head>
    <script>//State config</script>
  </head>
  <body>
    <p>hello container</p>
    <div>
      <!-- View html in here -->
    </div>
  </body>
</html>

id

Optional id for React to use as the base of the app. Default: app

In order for React to re-hydrate the DOM on the client it needs to know where it should attach itself. In a previous version of koa-react-router this was not possible. This property allows you to add a custom root id to the DOM. For example, if you set this to root, the output would look something like.

<html lang="en">
  <head>
    <script>//State config</script>
  </head>
  <body>
    <div id="root">
      <!-- View html in here -->
    </div>
  </body>
</html>

Router Context

React Router 4 added support for a static router context this context can be used in your application, to pass values from your router to other middleware and drive behaviour for routes.
koa-react-router makes this context available on the koa ctx in the following location:

ctx.state.routerContext;

One example of using this context is setting a status in the route context so a later middleware can set that as this response code. The common use case of status is already taken care of. So if one of your routes sets a status prop whilst rendering that will be set as the response status See Not found in the FAQ section for an example.
Use the routerContext for whatever you want in your app, some common recipes will be added to this repo at a later date.

FAQ

This release includes some deprecated props. As React Router has come with some major changes so has koa-react-router.

No more routes prop ?

The routes prop has gone in favour of the App config prop. Where you would have passed in your static routes before you can now pass in your App component that contains the React Router routes. For example:

// App.js
  import React from 'react';
  import { Route } from 'react-router';
  import Home from '../containers/Home';
  import Article from '../containers/Article';

  const App = () =>
    <div>
      <h1>This is my App!</h1>
      <Route path="/" component={Home} exact />
      <Route path="/article" component={Article} exact />
    </div>;

React Router 4 gives you the flexibility to define your routes wherever you want in your app, and so does koa-react-router.

What do I do with routes that are not found ?

The previous version of koa-react-router supported a onNotFound callback. This has been deprecated in favour of defining a status prop on the React Router static context and using a Switch component in your app. For example, our App component may be written as:

  import React from 'react';
  import { Route, Switch } from 'react-router';
  import Home from '../containers/Home';
  import Article from '../containers/Article';

  const NotFound = ({ status }) =>
    <Route
      render={({ staticContext }) => {
        if (staticContext) staticContext.status = status;
        return <div>This route has not been found Soz!</div>;
      }}
    />;

  const App = () =>
    <div>
      <h1>This is my App!</h1>
      <Switch>
        <Route path="/" component={Home} exact />
        <Route path="/article" component={Article} exact />
        <NotFound status={404} />
      </Switch>
    </div>;

If not other routes are matched the NotFound component will be rendered, and koa-react-router will set the response code status.