Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Router: Show progress while loading

I want to show a progress bar when I switch one route from another, I found this package: nprogress, for youtube-like progress.

My problem is implementing this using React Router. I somehow need to execute NProgress.start(); on every start of routing, and NProgress.done(); when loaded.

Is there a better way (like a middleware between route changes or route listener for the router), other then going thorugh each route and doing start() on the onEnter, and done() on the component's DidMount()?

like image 519
Gershon Papi Avatar asked Jul 06 '16 22:07

Gershon Papi


1 Answers

You may simply start with NProgress.start() in onEnter handler and finish in getComponent or getComponents where you can asynchronously load your component, e.g. with Webpack’s require.ensure.

Something like this:

  <Route
    path="path"
    onEnter={() => {
      NProgress.start();
    }}
    getComponent={(nextState, cb) => {
      require.ensure([], (require) => {
        const Component = require('./path/to/Component').default;
        cb(null, Component);
        NProgress.done();
      });
    }}
  />
like image 65
Bogdan Slovyagin Avatar answered Sep 29 '22 02:09

Bogdan Slovyagin