Skip to content

Instantly share code, notes, and snippets.

@damonYuan
Last active November 29, 2018 08:16
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save damonYuan/f6ede1bb98b95452d2d18fafb6ef74f5 to your computer and use it in GitHub Desktop.
Save damonYuan/f6ede1bb98b95452d2d18fafb6ef74f5 to your computer and use it in GitHub Desktop.
react server side rendering without redux (server side)
// Helper function: Loop through all components in the renderProps object // and returns a new object with the desired key
let getPropsFromRoute = (renderProps, componentProps) => {
let props = {};
let lastRoute = renderProps.routes[-1];
renderProps.routes.reduceRight((prevRoute, currRoute) => {
componentProps.forEach(componentProp => {
if (!props[componentProp] && currRoute.component[componentProp]) {
props[componentProp] = currRoute.component[componentProp];
}
});
}, lastRoute);
return props;
};
let renderRoute = (response, renderProps) => {
// Loop through renderProps object looking for 'requestInitialData'
let routeProps = getPropsFromRoute(renderProps, ['requestInitialData']);
if (routeProps.requestInitialData) {
// If one of the components implements 'requestInitialData', invoke it.
routeProps
.requestInitialData()
.then((data)=>{
// Ovewrite the react-router create element function
// and pass the pre-fetched data as initialData props
let handleCreateElement = (Component, props) =>(
<Component initialData={data} {...props} />
);
// Render the template with RoutingContext and loaded data.
response.render('index', {
reactInitialData: JSON.stringify(data),
content: renderToString(
<RouterContext createElement={handleCreateElement} {...renderProps} />
)
});
});
} else {
// No components in this route implements 'requestInitialData'.
// Simply render the template with RoutingContext and no initialData.
response.render('index', {
reactInitialData: null,
content: renderToString(<RouterContext {...renderProps} />)
});
}
};
export default renderRoute;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment