Categories
React Answers

How to avoid rendering multiple routes with React Router v4?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *