Search code examples
reactjsreact-router-v4

React Router v4 rendering component twice


Here is my Router Implementation

<BrowserRouter>
  <div>
    <Route exact path="/" component={ProfilesIndex} />
    <Route exact path="/profiles" component={ProfilesIndex} />
    <Route exact path="/profiles/new" component={ProfileEditor} />
    <Route exact path="/profiles/:id" component={ProfileEditor} />
  </div>
</BrowserRouter>

When I am browsing to /profiles/new path, it is rendering the ProfileEditor component twice. For every other route, it is working fine.

Can someone suggest how to fix this problem ?


Solution

  • I found the answer after browsing into multiple sections in Router Docs. Problem was it was matching multiple routes

    When user opens /profiles/new it matches two routes

    1. /routes/new
    2. /routes/:id

    Because :id is like a wildcard * and it also matches new word so both routes get matched and hence the component gets rendered twice.

    The solution is to wrap the routes with Switch if you do not want to match multiple routes.

    <BrowserRouter>
      <Switch>
        <Route exact path="/" component={ProfilesIndex} />
        <Route exact path="/profiles" component={ProfilesIndex} />
        <Route exact path="/profiles/new" component={ProfileEditor} />
        <Route exact path="/profiles/:id" component={ProfileEditor} />
      </Switch>
    </BrowserRouter>