How to avoid rendering multiple routes with React Router v4?

Sometimes, we want to avoid rendering multiple routes with React Router v4.

In this article, we’ll look at how to avoid rendering multiple routes with React Router v4.

How to avoid rendering multiple routes with React Router v4?

To avoid rendering multiple routes with React Router v4, we can use the Switch component.

For instance, we write

import {Switch} from 'react-router';

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

to wrap the Routes around the Switch component so that only one matched component is rendered at a time.

Conclusion

To avoid rendering multiple routes with React Router v4, we can use the Switch component.