Home > Enterprise >  Redirect to another route when accessing a route in react
Redirect to another route when accessing a route in react

Time:03-11

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.

CodePudding user response:

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

CodePudding user response:

If I understand it correctly then you want to redirect the user to login page if the user is not logged in.

So what you can do is, Instead of trying to do it using route, you can do it from the component which gets rendered when the user goes to /.

You can check in the useEffect hook that if the user exists then go to / else go to /login.

Use the example from below:

useEffect(() => {
  if(!user) {
    navigate('/')
  }
}, [user])  
  • Related