Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Router 4 and exact path with dynamic param

I have issues with component being displayed on every single path because React Router 4 isn't using exact for that route (or so it appears).

<Route path="/" exact component={Explore} />
<Route path="/about" component={About} />

// The one making problems
<Route
    path="/:username"
    exact={true}
    render={props => <Profile {...props} />}
/>

So when I go to http://example.com/about, my Profile component is still being rendered. I guess the problem is in the route as it expects param :username and that goes right after / (root). Am I doing something wrong? I could add another route for /:username, like /profile/:username, but I'd like to keep it the way it is, if it's possible.

like image 291
MerkisL Avatar asked Mar 04 '19 15:03

MerkisL


People also ask

Which props should you use to match exactly the path you have for routing?

The exact prop is used to define if there is an exactly the requested path.

What is exact path in react router?

React router does partial matching, so /users partially matches /users/create , so it would incorrectly return the Users route again! The exact param disables the partial matching for a route and makes sure that it only returns the route if the path is an EXACT match to the current url.

How do you grab URL parameters from within a component using react router?

Using React Router, when you want to create a Route that uses a URL parameter, you do so by including a : in front of the value you pass to Route 's path prop. Finally, to access the value of the URL parameter from inside of the component that is rendered by React Router, you can use React Router's useParams Hook.


1 Answers

Assuming that you are not using Switch. Switch will solve your problem because it will only render the first path that matches.

<Switch>
  <Route path="/about" component={About}/>
  <Route path="/:username" render={props => <Profile {...props} />} />
  <Route path="/" component={Explore} />
  <Route component={NotFoundPage} />
</Switch>
like image 58
AngelSalazar Avatar answered Sep 30 '22 01:09

AngelSalazar