I want to redirect to home page from every page in my app. So I add the below code:
<Switch>
<Route path="/login" component={Login} />
<Route path="/otp" component={Otp} />
<Layout>
<Suspense fallback={<LayoutSplashScreen />}>
<Redirect push to="/homePage" />
<ContentRoute
path="/homePage"
component={RequestTabel}
children={undefined}
render={undefined}
/>
<ContentRoute
path="/Register"
component={RegisterPage}
children={undefined}
render={undefined}
/>
.
.
.
</Layout>
</Switch>
Now, when I refresh every page then I go to home page but the current page reloads and after that, the app goes to home page. I don’t know why and I want to proofread it. I’ve searched a lot and I can the below link but I have to add it in all of my pages in the app and I think, it’s not the correct solution.
if (performance.navigation.type === 1) {
// page was just refreshed:
window.location.href = '/homePage';
}
I add other parts of related code to my question:
routes.tsx
export default function Routes() {
return (
<Switch>
<HashRouter>
<BasePage />
</HashRouter>
</Switch>
);
}
BasePage
is the above code that I’ve written first.
2
Answers
Your layout simply exists, calling
Redirect
every time.I am not sure which routing library you’re using. If it is
react-router-dom
, take a look at their documentation to route Layouts. The TL;DR (though you should definitely read) is that everything in a router needs to be inside aRoute
, you can’t have things being free like this.If it is some other library, like TanStack Router try to find their definition of routing.
As it stands, your
Redirect
component is always being called, which is why you are always being redirected. It needs to be conditioned in a route.The code is unconditionally rendering the
Redirect
component. If you would like"/homepage"
to be a sort of "default" route then the nested routes insideLayout
/Suspense
should also be wrapped in aSwitch
(the outerSwitch
will already be matching and renderingLayout
) and theRedirect
moved to the end of theSwitch
as a "catch-all" route to redirect users to"/homepage"
if they weren’t trying to access any other route.Example:
If you want the app to redirect to
"/homepage"
when it mounts then add auseEffect
hook to the first component under the router and issue an imperative redirect.Example: