Search code examples
reactjsreact-dom

Redirect to another route when accessing a route in react


I have a use case where i want to redirect from '/' route to /login whenever someone hits the '/' route. For more clarity i have an app that points to 'app.web.com/login' as the login page. When someone tries to access 'app.web.com' it should redirect to 'app.web.com/login'. I am using react router version 6 and this is what i have tried.

      <Routes>
        <Route path='/'>
          <Navigate to="/auth/login" />
        </Route>
        <Route path='auth' element={<AuthView />}>
          <Route path='login' element={<LoginView />} />
        </Route>
        <Route path='*' element={<NotFoundView />} />
      </Routes>

But it does not have the desired effect. I am pretty much just picking react up so i am sure there is an easy way to do this.


Solution

  • What you could do is make a small component which is rendered on the '/' route which redirects you to the login page.

    You could use the useHistory hook for that.

    Below is an example of how a component like that looks like.

    import React, { useEffect } from 'react';
    import { useHistory } from 'react-router-dom';
    
    export const RedirectToLogin: React.FC = () => {
        const history = useHistory();
    
        useEffect(() => {
            history.push('/auth/login');
        });
    
        return null;
    };
    

    Your router component would look like:

    <Routes>
        <Route path='/' element={<RedirectToLogin />} />
        <Route path='auth' element={<AuthView />}>
          <Route path='login' element={<LoginView />} />
        </Route>
        <Route path='*' element={<NotFoundView />} />
      </Routes