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 />
    }
 }} />
1
  • 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 stackoverflow.com/questions/47627818/… Commented Jun 7, 2018 at 12:56

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.