简体   繁体   中英

React-router different path same component

I have this particular use case and I cannot find any solution. I need to use the same component for different paths , unfortunately the paths have different lengths like described in the pattern below

/targetpath/:targetpathId
/somepath/:somepathId/targetpath/:targetpathId
/somepath/:somepathId/someotherpath/:someotherpathId/targetpath/:targetpathId

I don't want to write each route for each case because it does not scale... So I am trying to write the path dynamically in this way

<Switch>
  <Route
    path={`${match.url}/targetpath/:targetpathId`}
    component={Photo}
  />
  //Other routes...
</Switch>

But because the routes have variable lengths this does not work every time

I am trying with Regex but still no luck

Anyone that has encountered this problem?

It seems unwise to create routes in the this manner. You can simply define a different route that loads the same component.

<Route to='/path1' component={MyComponent} />
<Route to='/path2' component={MyComponent} />

Yes, it's a pain having to write each component out, but it's far more intuitive, and you're less likely to implement a bug.

Ok, I have solved like this, thanks to Drusto

path="(^.*)/targetpath/:targetpath"

But in general Christopher Ngo was right that is a bad routing design and therefore I have decided to get another approach

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM