6

I have seen various examples saying that when using React Router V4, you can wrap your <Route /> components in either a <Switch> component provided by React Router, or you can use any other element to contain your routes (such as a <div>).

What is the difference between these two approaches?

Examples:

<BrowserRouter>
  <div>
    <Route exact path="/login" component={LoginScreen} />
    <Route path="/loading" component={LoadingScreen} />
  </div>
</BrowserRouter>

VS

<BrowserRouter>
  <Switch>
    <Route exact path="/login" component={LoginScreen} />
    <Route path="/loading" component={LoadingScreen} />
  </Switch>
</BrowserRouter>
saricden
  • 1,382
  • 2
  • 20
  • 34

1 Answers1

11

<Switch/> components will only show the first matched child <Route/> for any given path. Other configs will show all matches.

Arman Charan
  • 4,717
  • 2
  • 18
  • 26
  • 2
    Correct me if I am wrong, exact will also do the same thing – bajran Dec 15 '18 at 01:56
  • Unfortunately not. Multiple routes can have matching `path` props and be concurrently returned under most configs, despite also having `exact={true}` @bajran – Arman Charan Jul 15 '20 at 01:46