What does Switch do?

Viewed 5553

I have the following code:

import {Route, Switch} from 'react-router-dom';

<Route exact path="/" component={Landing} />
<div className="container">
  <Route path="/register" render={() => (
    <Register {...this.props} />
  )}/>
  <Route path="/login" render={() => (
    <Login {...this.props}/>
  )}/>
  <Switch>
    <PrivateRoute path="/dashboard" component={Dashboard}/>
  </Switch>
  <Switch>
    <PrivateRoute path="/create-profile" component={CreateProfile}/>
  </Switch>

After the user logs in (using /login), he's been redirected to /dashboard. However, if I remove the <Switch> from the /dashboard, the user is still being redirected to /dashboard but that Dashboard component doesn't get rendered.

So how exactly does that <Switch> work?

1 Answers

Removing the Switch inclusively renders the Login and Dashboard component as direct children. After login, you are redirected to the '/dashboard' url but the Dashboard does not get re-rendered because both Routes match this path.

The Switch component exclusively renders the first child path that matches the current url.

Related