I’m using React-router and it works fine while I’m clicking on link buttons, but when I refresh my webpage it shows an empty white screen. And also there are no console warnings, and return 200 for all network calls.
When the project runs in the local, it is working fine. But after adding it to the server, I get a white screen when refreshing or typing the link manually.
And I found, this issue rises only with 2nd level paths.
-
https://sample.cc/sport —-> Works fine
-
https://sample.cc/sport/soccer —-> get the white screen when refreshing or manually enterying
I use react router version 6 and there are nested routing as well. I think the issue is happen with the webpack build. I saw this is a common problem. But in every solutions, there are nothing mentioned about the webpack.
This is my webpack for production.
module.exports = {
entry: path.join(__dirname, 'src', 'index.tsx'),
plugins: [
new HtmlWebpackPlugin({
template: path.join(__dirname, 'public', 'index.html'),
}),
],
module: {
rules: [
{
test: /.html$/,
use: ['html-loader'],
},
{
test: /.(tsx|ts|jsx|js)$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
presets: ['@babel/preset-env', ['@babel/preset-react', { 'runtime': 'automatic' }], '@babel/preset-typescript']
}
}
},
{
test: /.(jpe?g|png|gif|svg|ico)$/i,
type: 'asset/resource',
generator: {
filename: 'assets/images/[name].[ext][query]',
}
},
]
},
resolve: {
extensions: ['', '.ts', '.tsx', '.js', '.jsx'],
},
infrastructureLogging: {
debug: [(name: string) => name.includes('webpack-dev-server')],
},
optimization: {
minimize: true,
splitChunks: {
chunks: 'all',
},
usedExports: true,
minimizer: [new TerserPlugin(
{
extractComments: false
}
)]
},
output: {
path: path.resolve(__dirname, 'dist'),
clean: true
},
};
This is my router
const router = createBrowserRouter([
{
path: '/',
element: <ErrorBoundary><MainLayout/></ErrorBoundary>,
children: [
{
path: 'profile',
element: <ProtectedLayout><Profile/></ProtectedLayout>
},
{
path: 'sport',
element: <ProtectedLayout><SportLayout/></ProtectedLayout>,
children: [
{
path: 'soccer',
element: <Soccer/>
},
]
},
]
}
]);
I tried to solve this problem using vite. then it worked fine. I wonder, Is there any way to do this using webpack?
2
Answers
The issue was in the webpack config. Just added a public path.
link for official doc -> https://webpack.js.org/guides/public-path/
Can you share your React Router structure in App.tsx file
According to ReactJS official docs Router mapping should be like this.
Source: https://reactrouter.com/en/main/routers/create-browser-router