React Router v4 renders multiple routes

Complexity picture Complexity · May 16, 2017 · Viewed 19.6k times · Source

I'm creating an SPA and I'm trying to setup Routing in the application using the react-router-dom package version 4.1.1.

My Route Definition is below:

<BrowserRouter>
  <div>
    <Route exact path="/" component={Login} />
    <Route path="/login" component={Login} />
    <Route path="404" component={NotFound} />
    <Route path="*" component={NotFound} />
  </div>
</BrowserRouter>

Basically, I want to setup routing so that any request to a page for which no route is defined goes to the {NotFound} component.

How can this be achieved? The solution above renders both the Login and the NotFound component when requesting the /login page.

Kind regards

Answer

Taras Yaremkiv picture Taras Yaremkiv · May 16, 2017

here's an example from official tutorial, how to avoid rendering multiple routes

import { Switch, Route } from 'react-router

    <Switch>
      <Route exact path="/" component={Home}/>
      <Route path="/about" component={About}/>
      <Route path="/:user" component={User}/>
      <Route component={NoMatch}/>
    </Switch>