Skip to content

Instantly share code, notes, and snippets.

@damonYuan
Last active November 29, 2018 08:16
Show Gist options
  • Select an option

  • Save damonYuan/f6ede1bb98b95452d2d18fafb6ef74f5 to your computer and use it in GitHub Desktop.

Select an option

Save damonYuan/f6ede1bb98b95452d2d18fafb6ef74f5 to your computer and use it in GitHub Desktop.

Revisions

  1. Damon Yuan revised this gist Aug 5, 2016. No changes.
  2. Damon Yuan revised this gist Aug 5, 2016. No changes.
  3. Damon Yuan created this gist Aug 5, 2016.
    46 changes: 46 additions & 0 deletions renderRoute.js
    Original 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;