Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid redirecting twice (react-router-redux)?

I am using the next (5.0.0) version react-router-redux which is compatible with react-router 4.x.

My app has two pages /login and /home.

I am trying to redirect pages to /login if user visits a page not existing. This is my code

import { Route, Redirect } from 'react-router-dom';
import { ConnectedRouter, routerMiddleware, push } from 'react-router-redux';

ReactDOM.render(
  <Provider store={store}>
    <ConnectedRouter history={history}>
      <div>
        <Route path="/login" render={() => (
          isSignedIn ? <Redirect to="/home" /> : <Login />
        )}/>

        <Route path="/home" component={Home} />

        <Redirect to="/login" />
      </div>
    </ConnectedRouter>
  </Provider>,
  document.getElementById('root')
);

If I remove <Redirect to="/login" /> and if the user already signed in, when he opens the page /home, the app will go to home page directly, which is good.

However, with <Redirect to="/login" />, when the user opens the page /home, the app will first redirect to /login, then goes back to /home.

How can I avoid this redirecting twice? Thanks

like image 926
Hongbo Miao Avatar asked Sep 19 '25 00:09

Hongbo Miao


1 Answers

Make use of Switch so that the first matching route is rendered and nothing else

import {Switch} from 'react-router';

ReactDOM.render(
  <Provider store={store}>
    <ConnectedRouter history={history}>
      <Switch>
        <Route path="/login" render={() => (
          isSignedIn ? <Redirect to="/home" /> : <Login />
        )}/>

        <Route path="/home" component={Home} />

        <Redirect to="/login" />
      </Switch>
    </ConnectedRouter>
  </Provider>,
  document.getElementById('root')
);

What happens in your case is that even though /home matches, the Redirect is also executed.

like image 190
Shubham Khatri Avatar answered Sep 21 '25 14:09

Shubham Khatri