Home > Enterprise >  How to create a custom route to handle the redirection of routes in react
How to create a custom route to handle the redirection of routes in react

Time:11-18

I am using react-router where I have following code

       <Router basename={config.historyBasename}>
          <Routes>
            <Route path={routes.landingPage} element={<LandingPage />} />
            <Route
              path={routes.activateAccount}
              element={
                !document.referrer.length ? (
                  redirectTo(appUrls.home)
                ) : (
                  <Parent/>
                )
              }
            />
           
          </Routes>
        </Router>

Here, I am using redirectTo which I created custom method. Now here, I am trying to create a custom route which will do

              <Route
              path={routes.activateAccount}
              element={
                !document.referrer.length ? (
                  redirectTo(appUrls.home)
                ) : (
                  <Parent/>
                )
              }
            />

this. How can I create a custom route which will handle this ?

CodePudding user response:

The past couple of years, react-router-dom and react-router introduced the <Redirect /> component which essentially when rendered, redirects the user to a specified location.

For example:

<Route exact path="/">
    <Redirect to={"/home"} />
</Route>

redirect the user to /home whenever he arrives on /.

CodePudding user response:

Well you can use Redirect from react-router-dom for Conditionally Redirect to the Default Path

<Route
    path={routes.activateAccount}
    element={!document.referrer.length ? <Redirect to='/home' /> : <Redirect to='/second-route' />}
/>

For v6 you can use Navigate

<Route
    path={routes.activateAccount}
    element={
        !document.referrer.length ? (
        <Navigate replace to='/home' />
        ) : (
           <Navigate replace to='/second-route' />
        )
        }
    />

Please note however that this won't work when server rendering because the navigation happens in a React.useEffect().

Have a look at Redirects in React Router v6 for some deeper details.

  • Related