3

Im using React Router and React Loadable to code split my app based on route:

In App.js:

<Router>
    <Switch>
       <Route exact path="/page1" component={Component1Loader} />
       <Route exact path="/page2" component={Component2Loader} />

In Component1Loader:

import Loadable from 'react-loadable';

const LoadableComponent = Loadable({
    loader: () => import('./ActualComponent1'),
    loading: Loading,
});

export default class Component1Loader extends React.Component {
    render() {
        return <LoadableComponent {...this.props} />;
    }
}

In Component2Loader:

import Loadable from 'react-loadable';

const LoadableComponent = Loadable({
    loader: () => import('./ActualComponent2'),
    loading: Loading,
});

export default class Component2Loader extends React.Component {
    render() {
        return <LoadableComponent {...this.props} />;
    }
}

How can I preload components based on route? Eg from the front page most users will then navigate to /page1 so I would like to preload this.

When on /page1 I would then like to prefetch /page2.

1 Answer 1

3

The component created by Loadable exposes a static preload method. In your case you need to export each LoadableComponent and preload in appropriate file *.js you want to. Example:

import { LoadableComponent } from './Component1Loader'

// Preload here
LoadableComponent.preload()

...

<Router>
  <Switch>
    <Route exact path="/page1" component={Component1Loader} />
    <Route exact path="/page2" component={Component2Loader} />

https://github.com/jamiebuilds/react-loadable#preloading

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.