history.location.key
equivalent in v6? -- How to check if previous item in history stack exists in react router v6?
#9788
-
In our previous react-router v6 app we had code using const handleCancelModal = () => {
const doesAnyHistoryEntryExist = history.location.key
if(doesAnyHistoryEntryExist){
history.goBack()
}
else {
// no entry exists, we landed on the page via direct URL, there is no previous history so fallback to x
history.push('/some_url);
}
}; In react router v6, how do we check if there is any entry in the history stack since now there is no const handleCancelModal = () => {
const doesAnyHistoryEntryExist = ?????
if(doesAnyHistoryEntryExist){
navigate(-1)
}
else {
// no entry exists, we landed on the page via direct URL, there is no previous history so fallback to x
navigate('/some_url);
}
}; |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments 1 reply
-
In v6, you can inspect the const doesAnyHistoryEntryExist = location.key !== "default"; Ref: |
Beta Was this translation helpful? Give feedback.
-
In my case |
Beta Was this translation helpful? Give feedback.
-
oesn't work as expected if we navigate to a new tab using window.open() or with target='_blank'. This way app still doesn't have where to go back but location.key isn't equal to 'default' |
Beta Was this translation helpful? Give feedback.
In v6, you can inspect the
location
object returned by theuseLocation
hook for this use case. When the history stack is empty, thelocation.key
will have the value"default"
.Ref:
history
library docs