2

I'm using React Router 4.2.0. In my scenario I have to load different components in same url.

I have two components Login and Dashboard

when I run localhost:3000 component should load based on the localstorage flag.

I tried with following code It shows 404 page

 <Route path='*' component={NotFound} />
 <Route path="/" render={(props) => {
    if (localStorage.getItem('user')) { 
       return <Dashboard /> 
    }
    else {
       return <Login />
    }
 }} />
Maria Jeysingh Anbu
  • 3,164
  • 3
  • 34
  • 55
  • Its always better to have separate route for login, you can redirect to that route if the person is not loggedIn, Check this answer on how to perform authentication https://stackoverflow.com/questions/47627818/performing-authentication-on-routes-with-react-router-v4/47628941#47628941 – Shubham Khatri Jun 07 '18 at 12:56

1 Answers1

2

By default routes are matched in an inclusive manner (as many as possible). The wildcard catches everything, if you need to switch between them in an exclusive manner, you need to use the Switch component. In others words:

    <div className="App">
      <Switch>
        <Route path="/" component={Login}/>
        <Route path="*" component={NotFound} exact/>
      </Switch>
    </div>

The above will match the login page on the root, then fallback on the 404.

Ragul Parani
  • 621
  • 7
  • 22
adz5A
  • 2,012
  • 9
  • 10