react-router: [Bug]: useLocation inside doesn't return given location
What version of React Router are you using?
6.1.1
Steps to Reproduce
Full reproduction can be found here, it’s functionally similar to v5 modal gallery example: https://codesandbox.io/s/heuristic-rhodes-508k5?file=/src/App.js
Steps to replicate:
- Click on Post link
- Home page should now use previous “background” location
- Notice how
useLocationin Home still returns new location
Expected Behavior
useLocation inside <Routes location={location}> returns the prop location.
useLocation inside <Routes> returns the “correct” currently active location.
Actual Behavior
Both useLocation return “correct” currently active location (as the one corresponding to URL bar).
I.e issue seems to be that useLocation is not scoped, it only reads global location.
About this issue
- Original URL
- State: closed
- Created 3 years ago
- Reactions: 22
- Comments: 24 (4 by maintainers)
Hey folks - I checked in with @ryanflorence and he confirmed this is a bug, so we should be able to get #9094 merged shortly for release with
6.4.0👍I had to use a temporary workaround for now because this is blocking my huge release!
Routeswithlocationprop with customContextand pass the same prop into it.useLocationthat tries to figure out where it is based on context existence.Dadaa! Now
useLocationreturns the correctlocationin every situation!@liuhanqu Yup you’re right. But the issue here seems to be that there’s only one location in context.
I expect this behavior:
useLocationinside<Routes location={location}>returns the prop location.useLocationinside<Routes>returns the “correct” currently active location.This is particularly useful for when you have a modal that has its own URL. For example: https://v5.reactrouter.com/web/example/modal-gallery
The idea is that the components that are receiving the “background” location work as usual. They are not aware of the concept of background/foreground location. To be honest I have never come across a use case where the background location would need to access the “global” location.
The problem is that the components where we need this behavior are
<Route />and anything related to the location (e.g hooks). For example:In the source code we can see that indeed
useLocationdoes not use the injectedlocationprop. Without creating the custom hook like @gitcatrat described, you can do this:I expected #8008 to mention this issue as well.