chickadee
chickadee

Reputation: 301

React Router with Separate Pages

I have a separate login and main page where after the user logs in, they are transferred to main. I am using this:

import Main from './Main';    // Original <App /> page
import Login from './Login';  // New <Login /> page  

// In App component  

<Router>  
  <Switch>
    <Route exact path="/" component={Main} />  
    <Route path="/login" component={Login} />
    <Route component{NotFound} />
  </Switch>
</Router>

Which works so far, however if I want to access a "page" within the Main component:

<Route exact path="/users" component={Users} />

using something like localhost:3000/users in the URL, it goes to a blank page. The only way to access /users is to start off in the Main component, and click on a link or button that goes to /users.

Does anyone know of a proper approach to this? I would like to be able to access components within the URL but also have a separate login page.

If I change exact path='/' to just path='/' it can work, but then I lose any sort of catch-all for not-found pages.

Upvotes: 1

Views: 1215

Answers (2)

Syed Osama Maruf
Syed Osama Maruf

Reputation: 1935

Take a look at the code below to achieve your desired result:

               <Switch>                  
                {this.props.notLoggedIn === true
                  ? <Route path='/' component={LandingPage}/>                                          
                  : <Dashboard />                    
                }
                <Route component={PageNotFound}/>
              </Switch>    

In the above case I show the landing page as the default route and in case the user is logged in the dashboard is shown (contains more routes). For details take a look at the answer here

Upvotes: 1

Jemika Negara
Jemika Negara

Reputation: 64

You should put the <Route exact path="/users" component={Users} /> in the App Component not in the Main Component

The <Route> define what component should be rendered while <Link to> define the url we will go after clicking. If you put the Route inside the Main Component, then it need to load Main Component first to define the route

Upvotes: 1

Related Questions