Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

react-router middleware for koa 2.

License

NotificationsYou must be signed in to change notification settings

afenton90/koa-react-router

Repository files navigation

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

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

Usage

To installkoa-react-router:

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

Note:reactreact-dom &react-router are allpeerDependencies ofkoa-react-router.

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

// index.jsimportKoafrom'koa';importreactrouterfrom'koa-react-router';importAppfrom'./App';importContainerfrom'./containers/PageContainer';constapp=newKoa();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

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

// App.jsimportReactfrom'react';import{Route}from'react-router';importHomefrom'../containers/Home';importArticlefrom'../containers/Article';constApp=()=><div><h1>This is my App!</h1><Routepath="/"component={Home}exact/><Routepath="/article"component={Article}exact/></div>;// index.js// ...importsimportAppfrom'./App';// ... koa app setupapp.use(reactrouter({    App,// Other callbacks}));

preRender

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

  • component - TheStaticRouter wrapped around theApp.

This callback could be used to wrap thecomponent 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 KoaContext object.
  • err - The error that was caught when matching routes.

onRedirect

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

  • ctx - The KoaContext 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 usingrenderToStaticMarkup.
The component must accept thechildren prop and insert it when rendered.For example:

// ./containers/ContainerimportReactfrom'react';constContainer=(props)=><htmllang="en"><head><title>Hello Container</title></head><body><divid="app">{props.children}</div></body></html>;exportdefaultContainer;

This would then be supplied tokoa-react-router via theonRender callback like so:

// index.jsimportKoafrom'koa';importreactrouterfrom'koa-react-router';importAppfrom'./App';importContainerfrom'./containers/Container';constapp=newKoa();app.use(reactrouter({    App,onRender:(ctx)=>({ Container})}));

As well as theContainer property this callback can optionally return:

containerRenderer

Optional function for handling the rendering of a container component.
This function has one argument which isview. 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 theContainer property when returning fromonRender.
For example you may want to render the container as follows:

// index.jsimportKoafrom'koa';importreactrouterfrom'koa-react-router';// ...other importsconstapp=newKoa();conststate=// Create state.app.use(reactrouter({    App,onRender:(ctx)=>({containerRenderer:(view)=><htmllang="en"><head><scriptdangerouslySetInnerHTML={{__html:state}}/></head><body><p>hello container</p><divdangerouslySetInnerHTML={{__html:view}}/></body></html>})}));

The final page render would look something like:

<htmllang="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 ofkoa-react-router this was notpossible. This property allows you to add a custom root id to the DOM. For example, if you set this toroot, the output would look something like.

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

Router Context

React Router 4 added support for astatic 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 koactx in the following location:

ctx.state.routerContext;

One example of using this context is setting astatus 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 astatus prop whilst rendering that will be set as the response status SeeNot found in the FAQ section for an example.
Use therouterContext 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 haskoa-react-router.

No more routes prop ?

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

// App.jsimportReactfrom'react';import{Route}from'react-router';importHomefrom'../containers/Home';importArticlefrom'../containers/Article';constApp=()=><div><h1>This is my App!</h1><Routepath="/"component={Home}exact/><Routepath="/article"component={Article}exact/></div>;

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

What do I do with routes that are not found ?

The previous version ofkoa-react-router supported aonNotFound callback. This has been deprecated in favour of defining astatus prop on the React Router static context and using aSwitch component in your app. For example, ourApp component may be written as:

importReactfrom'react';import{Route,Switch}from'react-router';importHomefrom'../containers/Home';importArticlefrom'../containers/Article';constNotFound=({ status})=><Routerender={({ staticContext})=>{if(staticContext)staticContext.status=status;return<div>This route has not been found Soz!</div>;}}/>;constApp=()=><div><h1>This is my App!</h1><Switch><Routepath="/"component={Home}exact/><Routepath="/article"component={Article}exact/><NotFoundstatus={404}/></Switch></div>;

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

About

react-router middleware for koa 2.

Topics

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Contributors3

  •  
  •  
  •  

[8]ページ先頭

©2009-2025 Movatter.jp