0

In ReactJS , I have this routes:

<Route exact path="/" component={Home}/>
<Route path="/:id" component={Profile}/>
<Route path="/settings" component={Settings}/>

when I request

www.example.com/username

I get the Profile component as expected, but the problem is when I request

www.example.com/settings

the page render two components at the same time first I get the Profile component and below it, I get Settings component

how can I handle this case in React JS?

2 Answers2

2

Since both location path are same, you need to use exact, so you may use like this:

<Route exact path="/" component={Home}/>
<Route exact path="/settings" component={Settings}/>
<Route path="/:id" component={Profile}/>

But why not use profile path like this?

<Route path="/profile/:id" component={Profile}/>

A much better experience.

Bhojendra Rauniyar
  • 73,156
  • 29
  • 131
  • 187
0

add <Switch> tag to avoid rendering multiple routes

import {BrowserRouter, Route, Switch} from "react-router-dom";
<BrowserRouter>
       <div className="sans-serif">
          <Switch>
             <Route exact path="/" component={Home}/>
             <Route path="/settings" component={Settings}/>
             <Route path="/:id" component={Profile}/>
          </Switch>
        </div>
</BrowserRouter>