'React Browser Router v6 not rendering element on refresh
Routing seems to be working fine until I go to a child route and refresh the page. After refreshing the page the element disappears and the only way to fix it is to go to the base route and refresh the page. I have the entire app wrapped around BrowserRouter in the index.js file.
Index.js
import React from 'react';
import {createRoot} from 'react-dom/client';
import App from './App';
import {BrowserRouter} from "react-router-dom";
const mount = (element) => {
createRoot(
element,
).render(
<React.StrictMode>
<BrowserRouter>
<App/>
</BrowserRouter>
</React.StrictMode>
);
};
if (process.env.NODE_ENV === 'development') {
const devRoot = document.querySelector('#_marketing-dev-root');
if (devRoot)
mount(devRoot);
}
export {mount};
App.js file
import React from 'react';
import {Routes, Route, BrowserRouter} from "react-router-dom";
import {createTheme, ThemeProvider, StyledEngineProvider} from '@mui/material/styles';
import Landing from './components/Landing';
import Pricing from './components/Pricing';
const mdTheme = createTheme();
export default () => {
return (
<div>
<StyledEngineProvider injectFirst>
<ThemeProvider
theme={mdTheme}
>
<Routes>
<Route path="/" element={<Landing/>}/>
<Route path="pricing" element={<div>Hello</div>}/>
</Routes>
</ThemeProvider>
</StyledEngineProvider>
</div>
);
};
In the Landing component I have some links that looks like:
<Grid item>
<Link to="pricing">
<Button variant="contained" color="primary">
Pricing
</Button>
</Link>
</Grid>
<Grid item>
<Link to="pricing">
<Button variant="outlined" color="primary">
Pricing
</Button>
</Link>
</Grid>
Clicking on these links route me to the correct element. But, once I get to that element and refresh the page it just disappears. No errors or warnings in the console.
Solution 1:[1]
Thanks for all the suggestions everyone. I found out it was a webpack preference that was causing this issue.
Old Webpack preference
devServer: {
port: 8081,
historyApiFallback: {
index: 'index.html',
},
},
New Webpack preference
devServer: {
port: 8081,
historyApiFallback: true,
},
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Caleb Mills |
