score:1

Accepted answer

use matchpath for react router 4+

as noted above, though off topic from your question... you should be using staticrouter for react router 4

app.get("*", ( request, response ) => {
const store = configurestore();

const promises = routes.reduce((acc, route) => {
    if (matchpath(request.url, route) && route.component && route.component.initialaction) {
        acc.push(promise.resolve(store.dispatch(route.component.initialaction())));
    }
    return acc;
}, []);

promise.all(promises)
    .then( () => {
        const context={};
        const markup = rendertostring(
          <provider store={store}>
              <staticrouter location={request.url} context={context}>
                  <app />
              </staticrouter>
          </provider>
        );

        const initialdata = {};

        response.send(`
            <!doctype html>
            <html class="no-js" lang="en">
                <head>
                </head>
                <body>  
                    <div id="root">${markup}</div>
                    <script src="/app.bundle.js" defer></script>
                    <script>window.__initialdata__ = ${serialize(initialdata)}</script>
                </body>
            </html>`);

    });
});

i use this to call the initialaction method (which is static) on any components where i might want to preload the data for the component on the server side. however you can write all of your components without this method and the code below will work just the same.

note that the routes is an object in another file e.g.

import home from "./components/home";

const routes = [
    {
        path: "/",
        exact: true,
        component: home
    }
];

export default routes;

Related Query

More Query from same tag