React lazy components not loaded on dynamic routes
I think, no problem in use of react Suspense or lazy. just use Switch
in a wrong way.
As react router doc say:
All children of a
<Switch>
should be<Route>
or<Redirect>
elements. Only the first child to match the current location will be rendered.
So, Switch
component may not recognize the Route which wrapped by the Suspense component.
eg:
import Loader from './path/toFile';
import Home from './path/toFile';
const LazyLoadedComponent = lazy(() => import('./path/toFile'));
const App = () => {
return(
<Router>
<Suspense fallback={Loader}>
<Switch>
<Route exact path="/:viewType?" component={Home} />
<Route path="/viewType/:selectionId" component={LazyLoadedComponent} />
</Switch>
</Suspense>
</Router>
)
}
Here is a example in code sandbox: https://codesandbox.io/s/async-react-router-v4-w-suspense-8p1t6
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.