Search code examples
reactjsreact-routerreact-router-dom

How to prevent current page reload and go to home page in React?


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.


Solution

  • The code is unconditionally rendering the Redirect component. If you would like "/homepage" to be a sort of "default" route then the nested routes inside Layout/Suspense should also be wrapped in a Switch (the outer Switch will already be matching and rendering Layout) and the Redirect moved to the end of the Switch as a "catch-all" route to redirect users to "/homepage" if they weren't trying to access any other route.

    Example:

    <Switch>
      <Route path="/login" component={Login} />
      <Route path="/otp" component={Otp} />
      <Layout>
        <Suspense fallback={<LayoutSplashScreen />}>
          <Switch>
            <ContentRoute path="/homePage" component={RequestTabel} />
            <ContentRoute path="/Register" component={RegisterPage} />
              ...
              ...
              ...
            <Redirect push to="/homePage" />
          </Switch>
        </Suspense>
      </Layout>
    </Switch>
    

    If you want the app to redirect to "/homepage" when it mounts then add a useEffect hook to the first component under the router and issue an imperative redirect.

    Example:

    import { useHistory } from 'react-router-dom';
    
    const App = () => {
      const history = useHistory();
    
      React.useEffect(() => {
        history.replace("/homepage");
      }, []);
    
      ... rest of the component code
    };
    
    <BrowserRouter>
      <App />
    </BrowserRouter>