Ad

React Lazy Components Not Loaded On Dynamic Routes

I used react lazy and suspense on dynamic routes but somehow I cannot render the lazy loaded components.

I've already searched about the use of lazy on routes but I haven't seen anyone use it on dynamic(localhost:8080/dynamic/dynamic) routes.

loading components on dynamic routes works for me, lazy loading also works if I have a static route, but when I tried combining the two, the component doesn't load.

here is an example of what I did,

import Loader from './path/toFile';
import Home from './path/toFile';
const LazyLoadedComponent = lazy(() => import('./path/toFile'));

const App = () => {
 return(
  <Router>
     <Switch>

        // Home has multiple views controlled by buttons
        // A view contains selections with corresponding id
       <Route exact path="/:viewType?" component={Home} /> 

       // this component doesn't load when I select something which links me to this dynamic route.
       <Suspense fallback={Loader}>
         <Route path="/viewType/:selectionId" component={LazyLoadedComponent} />
       </Suspense>

     </Switch>
   </Router>
 )
}

I just want my component to be loaded once I go to that route. But the Result is that it loads Home but when I select one from the selection it just shows the index.html with blank I haven't seen any error produced.

Ad

Answer

I have found the solution.. or sort of in my case.

I included the publicPath of for my bundles.

I added this on my webpack.config.js

output: {
        publicPath: '/',
      },

and the problem why it didn't work last time is that I'm just refreshing the page knowing have hotmodule installed but it doesn't update my configurations.

So after restarting the server I saw the line

webpack output is served from (the publicPath I declared)

Though I've spent more time than I should have in this problem. It's working now thanks for all of the comments.

Ad
source: stackoverflow.com
Ad