ReactJS RoutingContext

I am creating an isomorphic application using ReactJS with react-router for server-side routing purposes.

From the guide on using a reactive router on a 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 for me it is a little unclear how this works. Is this some kind of replacement for the Router component from the responsive router (used on top of other routes)?

Any help in understanding would be truly appreciated!

+5
source share
3 answers

React router v4

in the new version (v4) it is updated to createServerRenderContext . This works in a completely different way than before, but much more concise, as it also eliminates the need to use a β€œmatch”.

this code example should be used as 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 application showing how to do universal rendering using createServerRenderContext

+2
source

RoutingContext is an undocumented function and will be replaced by RouterContext in version 2.0. Its role is to synchronously display the route component.

It is just a wrapper around your component that introduces context properties such as history , location and params .

+1
source

React router v4

in the new version (v4) it has been removed for createServerRenderContext. This works in a completely different way than before, but much more concise.

this small code example should be applied.

 import { StaticRouter } from'react-router-dom' const context = {} const mockup = renderToString( <Provider store = {store}> <IntlProvider locale = {locale} messages = {messages[locale]}> <StaticRouter location={request.url} context={context}> <ModuleReactWithPages /> </StaticRouter> </IntlProvider> </Provider> ) 

Now this is a layer of himself when he is 404

0
source

Source: https://habr.com/ru/post/1240530/


All Articles