react-router
react-router copied to clipboard
[Docs]: Clarify route-hierarchy-awareness of useResolvedPath versus resolvedPath
What version of React Router are you using?
6.3.0
Steps to Reproduce
In a component at path /static/firms/3da097ce-ae52-4c6d-b7fd-0c7583708631/organizations/181bea0b-1748-44db-ba16-f2329862d989
const location = useLocation()
const { pathname } = useResolvedPath('..')
console.log(pathname) // `/static/firms/3da097ce-ae52-4c6d-b7fd-0c7583708631` <-- incorrect path
console.log(resolvePath('..', location.pathname).pathname) `/static/firms/3da097ce-ae52-4c6d-b7fd-0c7583708631/organizations` <-- correct path
Different resolved paths
Expected Behavior
Both the useResolvedPath and resolvePath provide equivalent results
Actual Behavior
resolvePath('..', location.pathname).pathname provides the correct pathname Im looking for.
useResolvedPath('..') provides an incorrect path in my example with two path sections removed
I think this is route-hierarchy related. Relative routing is done in react-router based on the route hierarchy, not the URL segments. useResolvedPath is thus doing it's relative routing via the hierarchy. resolvePath is not component aware so it can only operate on the URL split on slashes.
My hunch is that you're using a route hierarchy like the following:
<Route path="static">
<Route path="firms/:firmId">
<Route path="organizations/:ordId" element={<Org />} />
</Route>
</Routes>
In which case it is correct for useResolvedPath('..') to produce the path for the parent Route - /static/firms/{firmId}.
If that's the case and you need to get just the parent, you can adjust your hierarchy to the following to force useResolvedPath('..') to only remove the orgId portion of the route path.
<Route path="static">
<Route path="firms/:firmId">
<Route path="organizations">
<Route path=":orgId" element={<Org />} />
</Route>
</Route>
</Routes>
Ahh yea. Thanks @brophdawg11 ! im definitely using some multi-segment relative paths. If this is a feature of the useResolvedPath hook, I think it should be clarified in the documentation as it currently reads/implies that its just a convenience wrapper around resolvePath