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);
}
}; |
Answered by
krisheinrich
Jan 5, 2023
Replies: 3 comments 1 reply
|
In v6, you can inspect the const doesAnyHistoryEntryExist = location.key !== "default";Ref: |
1 reply
Answer selected by
cliffordfajardo
|
In my case |
0 replies
|
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' |
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
In v6, you can inspect the
locationobject returned by theuseLocationhook for this use case. When the history stack is empty, thelocation.keywill have the value"default".Ref:
historylibrary docs