4

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

Hongbo Miao
  • 45,290
  • 60
  • 174
  • 267
  • Why not configure a route for Home and then redirect to login is the user is not logged in from within Home component – Shubham Khatri Jul 30 '17 at 07:59
  • Hi @ShubhamKhatri, I didn't get it, can you explain more? Thanks – Hongbo Miao Jul 30 '17 at 08:04
  • See this question to check for loggin in Home https://stackoverflow.com/questions/44127739/programatically-routing-based-on-a-condition-with-react-router/44128108#44128108 and redirect And I mean You can have a route like `` – Shubham Khatri Jul 30 '17 at 08:06
  • Sorry, my mistake, actually it is already like that, I just updated. But still does not work. – Hongbo Miao Jul 30 '17 at 08:15

1 Answers1

5

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.

Shubham Khatri
  • 270,417
  • 55
  • 406
  • 400
  • As I said in my comment, you can keep the logic of redirecting to login in the Home component. Refer to https://stackoverflow.com/questions/44127739/programatically-routing-based-on-a-condition-with-react-router/44128108#44128108 – Shubham Khatri Jul 30 '17 at 10:43