-
-
Save bisubus/662a34732acff2fddc3d8997f2ac8217 to your computer and use it in GitHub Desktop.
react server side rendering without redux (server side)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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