Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ReactJS react-router RoutingContext

I'm building isomorphic application using ReactJS with react-router module for routing purposes on server side.

From its guide about using react-router on server:

(req, res) => {      
  match({ routes, location: req.url }, (error, redirectLocation, renderProps) => {
    //...

    else if (renderProps) {
      res.status(200).send(renderToString(<RoutingContext {...renderProps} />))
    } 

    //...
  })
}

There is almost no information about this RoutingContext. So it's a bit unclear for me how it works. Is it some kind of replacement for Router component from react-router (used on top of other routes)?

Any help in understanding will be really appreciated!

like image 576
oleh.meleshko Avatar asked Jan 13 '16 13:01

oleh.meleshko


2 Answers

React router v4

in the new version (v4) it has been updated to createServerRenderContext. This works in very different way than previously but is much more concise as it also get rid of the need for using 'match'.

this code example is to be applied as express middleware:

import React from 'react';
import { renderToString } from 'react-dom/server';
import { ServerRouter/* , createServerRenderContext */ } from 'react-router';
// todo : remove line when this PR is live
// https://github.com/ReactTraining/react-router/pull/3820
import createServerRenderContext from 'react-router/createServerRenderContext';
import { makeRoutes } from '../../app/routes';

const createMarkup = (req, context) => renderToString(
  <ServerRouter location={req.url} context={context} >
    {makeRoutes()}
  </ServerRouter>
);

const setRouterContext = (req, res, next) => {
  const context = createServerRenderContext();
  const markup = createMarkup(req, context);
  const result = context.getResult();
  if (result.redirect) {
    res.redirect(301, result.redirect.pathname + result.redirect.search);
  } else {
    res.status(result.missed ? 404 : 200);
    res.routerContext = (result.missed) ? createMarkup(req, context) : markup;
    next();
  }
};

export default setRouterContext;

react-lego is an example app that shows how to do universal rendering using createServerRenderContext

like image 177
peter.mouland Avatar answered Oct 31 '22 23:10

peter.mouland


RoutingContext is an undocumented feature and will be replaced by RouterContext in v2.0.0. Its role is to synchronously render the route component.

It is simply a wrapper around your component which inject context properties such as history, location and params.

like image 2
Florent Avatar answered Nov 01 '22 01:11

Florent