Reputation: 2109
We're using react 16.13 and react-router-dom 5.1.2 but we struggle to make it work the way we want:
/
and not page1/
(We've configured the nodejs/express backend to send the react app no matter the route)
So react-router just adds all the history / path to the /page1
url, resulting in /page1/login
, /page1/page1
, etc. instead of the /login
or /page1
urls.
Is there any way to achieve that? The goal is to allow the refresh of the page, and to allow direct access to a specific route.
EDIT: code example
client side
<StoreProvider store={store}>
<Suspense fallback={<MainPageFallback />}>
<ThemeProvider theme={theme}>
<Router basename={location.pathname}>
<I18nextProvider i18n={i18next}>
<TryCatch>
<Navbar actions={<UserSettings />} />
<div className={classes.appContent}>
<Switch>
<Route exact path="/start">
<LandingPage />
</Route>
<Route exact path="/search">
<SearchPlacePage />
</Route>
<Route exact path="/signup">
<SignUpPage />
</Route>
<Route exact path="/signin">
<LoginPage />
</Route>
<Route exact path="/forgot_password" component={ForgotPassword} />
<Redirect from="/*" to="/start" />
</Switch>
<Snackbar />
</div>
</TryCatch>
</I18nextProvider>
</Router>
</ThemeProvider>
</Suspense>
</StoreProvider>
server side
@Route('/*')
public async home({ query }: Request, res: Response) {
const { resolve } = await import('path');
const { readFileAsync } = await import('../Infrastructure/readFileAsync');
try {
const file = (await readFileAsync(resolve(__dirname, '..', '..', '..', 'static', 'index.html')))
.toString('utf-8');
return res.send(file);
} catch (err) {
return res.sendFile(resolve(__dirname, '..', '..', '..', 'static', 'notFound.html'));
}
}
Upvotes: 0
Views: 155
Reputation: 387
You need to use Routes
rather than Switch
for react-router-dom@6. Something like this:
<BrowserRouter>
<Routes>
<Route path="/" element={<App />}>
</Route>
</Routes>
</BrowserRouter>
Upvotes: 1