I have a React App using React Router. I have a /inventory page and another at /inventory/edit. Here's the Switch I set up for all my pages:
ReactDOM.render(
<Router>
<Switch>
<Route exact path='/' component={Home}/>
<Route exact path='/store' component={Store}/>
<Route exact path='/contact' component={Contact}/>
<Route exact path='/admin' component={Admin}/>
<Route exact path='/login' component={Login}/>
<Route exact path='/register' component={Register}/>
<Route exact path='/inventory' component={Inventory}/>
<Route exact path='/inventory/edit' component={EditItem}/>
<Route component={NotFound} />
</Switch>
</Router>,
document.getElementById('root')
);
I can navigate to the edit page using a Link (<Link to={{pathname: '/inventory/edit'}}>) but if I type the URL into the browser address bar nothing is rendered and I'm left with a blank page. I noticed that in the browser console I get an error saying:
Uncaught SyntaxError: Unexpected token < bundle.js:1
So I'm not sure if its a problem with using Webpack or if its unrelated to that. I've also noticed that this happens with anything manually typed into the address bar that has more than one slash, so while /store works, /store/test will also show up blank. I want /inventory/edit to bring me to the correct page, but /store/test should bring me to my 404 page.
I've searched around but haven't found anything like this online. If anyone can point out what I'm doing wrong here that'd be great.
EDIT (Solution)
I had to change all the paths defined in my index.html file from ./foo/bar to /foo/bar, which I figured out from Garry Taylor's comment.
Other solutions:
From here: React Router not working when URL contains multiple paths In your webpack config file, add an output configuration and set the publicPath to /. i.e
output:{
publicPath: '/'
}
For completion sake, you can also add the publicPath in the devServer config if you have one (optional). i.e
devServer:{
...
publicPath:'/'
}
Adding the HTML base tag to the header section of your index.html file should provide the same result. i.e
<base href="/">
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With