I have a React app with navigation powered by react-router
that I run in development with webpack-dev-server
and the history fallback option enabled. Here is the routes I have defined in my index.js
ReactDOM.render((
<Router history={browserHistory}>
<Route path="/" component={App}>
<IndexRedirect to="/intro" />
<Route path="/intro" component={Intro} />
<Route path="/device" component={Device} />
<Route path="/clothing" component={Clothing} />
<Route path="/build" component={Build}>
<IndexRedirect to="/build/pattern" />
<Route path="/build/pattern" component={Pattern} />
<Route path="/build/layout" component={Layout} />
<Route path="/build/color" component={Color} />
</Route>
<Route path="/capture" component={Capture} />
<Route path="/review" component={Review} />
</Route>
</Router>
), document.getElementById('app'))
When I navigate through links, everything works fine and I can see the nested route components nesting within their parent route components as expected. For example when I navigate to /build/color
I can see my App
component nesting the Build
component nesting the Color
component.
Where it fails is when I try to hit the refresh button within the nested route. React entirely fails to load and I get the following error
GET http://localhost:8080/build/app.js 404 (Not Found)
There is indeed not such a file in my app but I am still confused as of why it is automatically looking for this file instead of reloading the route from the root. Note that hitting refresh on pages like /device
does work without an issue.
Let me know if you need more details about my setup. Thanks!
Solution:
My webpack
setup is actually using HtmlWebpackPlugin
which was injecting the path to my app bundle as follows
<script src="app.js" type="text/javascript"></script>
All I needed to do was to configure my webpack
public path as publicPath: '/'
so that the bundle would be injected as follows
<script src="/app.js" type="text/javascript"></script>
It doesn't work because it can't load your javascript bundle. I'm guessing that the problem is with your path in script tag in HTML. Probably you have specified the path to app.js with dot at the beginning like this one
<script src="./app.js"></script>
, if this is true please remove dot and check if the problem still exists <script src="/app.js"></script>
Let's illustrate what is the difference between ./app.js
and /app.js
Case 1. You are loading page using first level of routes like /
or /intro
./app.js
: HTML tries to load script from http://address/app.js
/app.js
: HTML tries to load script from http://address/app.js
No difference
Case 2. You are loading page using second level of routes /build/pattern
./app.js
: HTML tries to load script from http://address/build/app.js
- doesn't exist/app.js
: HTML tries to load script from http://address/app.js
- OK