Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 874
Sachin Avatar asked Jan 27 '23 10:01

Sachin


1 Answers

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>
like image 196
Sachin Avatar answered Jan 31 '23 23:01

Sachin