Search code examples
reactjsreact-routerreact-router-v4react-router-domreact-loadable

Code splitting with React Loadable and routes with containers


I want to achieve code splitting of every main route so every page will have its own file (along with its subcomponents), for example I have a main render function with Route components that points to containers:

    <Route path={`path1`} component={foo.container} />
    <Route path={`path2`} component={bar.container} />

Each container looks something like this:

const mapDispatchToProps = {
... actions etc ...
}

const mapStateToProps = (state) => ({
... selectors etc ...
})

const withConnect = connect(mapStateToProps, mapDispatchToProps);

export default compose(withConnect)(MyComponent);

I tried to wrap a container and reference that in the route but it didn't work:

export default Loadable({
  loader: () => import('./MyContainer'),
  loading() {
    return (<div>Loading...</div>)
  },
});

So what am supposed to wrap then?


Solution

  • Here is a simplified example how to achieve code splitting with react-router and react-loadable:

    MyPage.jsx - the page what you want to generate in a separate file

    import React from 'react';
    
    const MyPage = () => (
        <div>My page</div>
    );
    
    export default MyPage;
    

    LoadableMyPage.jsx - wrapper to make your page loadable

    import React from 'react';
    import Loadable from 'react-loadable';
    
    const LoadableMyPage = Loadable({
        loader: () => import('./MyPage'),
        loading: () => <div>Loading...</div>,
    });
    
    const LoadableMyPage = () => (
        <LoadableMyPage />
    );
    
    export default LoadableMyPage;
    

    Router.jsx

    import React from 'react';
    import { Switch, Route } from 'react-router-dom';
    import LoadableMyPage from './LoadableMyPage';
    
    const Router = () => (
        <Switch>
            <Route path="/" exact component={LoadableMyPage} />
            ...
        </Switch>
    );
    

    As @Mohit Tilwani mentioned, the dynamic import plugin is required because it's currently in stage-3 and not part yet of the ECMAScript.

    https://github.com/tc39/proposal-dynamic-import

    I started working on my own React boilerplate where I implemented the same code splitting. Do not hesitate to check it if you got stucked.

    https://github.com/peetya/react-boilerplate