Last active
November 29, 2018 08:16
-
-
Save damonYuan/f6ede1bb98b95452d2d18fafb6ef74f5 to your computer and use it in GitHub Desktop.
Revisions
-
Damon Yuan revised this gist
Aug 5, 2016 . No changes.There are no files selected for viewing
-
Damon Yuan revised this gist
Aug 5, 2016 . No changes.There are no files selected for viewing
-
Damon Yuan created this gist
Aug 5, 2016 .There are no files selected for viewing
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 charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,46 @@ // 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;