Reputation: 51
Not sure what is happening here. I have set up my routing and when I go to my first page localhost:8080/ the first route renders as expected. However if I enter into the url in localhost:8080/store the expected route fails and I receive a 404 cannot find (doesnt even fallback to my not found component).
However if I set up a Link to and click the link it will render my store route as expected.
Shouldn't /store
render out my StorePicker component regardless if its entered into the URL or selected via a Link to element?
App.js
import React, { Component } from 'react';
import ReactDOM, { render } from 'react-dom';
import { BrowserRouter as Router, Route, Link, Switch } from 'react-router-dom';
//Components
import StorePicker from './components/StorePicker.js';
import Main from './components/Main';
import NotFound from './components/NotFound';
const Routes = () => {
return (
<Router>
<div>
<Link to="/store">Store</Link>
<Switch>
<Route path="/" exact component={StorePicker} />
<Route path="/store" component={Main} />
<Route component={NotFound} />
</Switch>
</div>
</Router>
)
}
render(<Routes />, document.querySelector('#container'));
Upvotes: 4
Views: 1531
Reputation: 35276
Assuming you're using Webpack. If so, adding a few things to your webpack config should solve the issue. Specifically, output.publicPath = '/'
and devServer.historyApiFallback = true
.
var path = require('path');
var HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
entry: './app/index.js',
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'index_bundle.js',
publicPath: '/'
},
module: {
rules: [
{ test: /\.(js)$/, use: 'babel-loader' },
{ test: /\.css$/, use: [ 'style-loader', 'css-loader' ]}
]
},
devServer: {
historyApiFallback: true,
},
plugins: [
new HtmlWebpackPlugin({
template: 'app/index.html'
})
]
};
Upvotes: 3