[v6] Check if you can go back #8782
Replies: 7 comments 8 replies
-
You can pass the previous route in a state const { pathname } = useLocation()
return <Link to={{ pathname: '/page, state: { prevPage: location.pathname }}}>To Page</Link> and check against it like const { state } = useLocation()
return (
<section>
{!!state.prevPage && <BackButton ?>}
<main>Content</main>
</section>
) |
Beta Was this translation helpful? Give feedback.
-
I guess you need to store the navigation history in a stack, and check it by yourself. // listen history change and store it
function useHistoryStack() {
const [stack, setStack] = useState([]);
const { pathname } = useLocation();
const type = useNavigationType();
useEffect(() => {
if (type === "POP") {
setStack(stack.slice(0, stack.length - 1));
} else if (type === "PUSH") {
setStack([...stack, pathname]);
} else {
setStack([...stack.slice(0, stack.length - 1), pathname]);
}
}, [pathname, type]);
return stack;
} and you can check the length of the stack
|
Beta Was this translation helpful? Give feedback.
-
I ran into this just today - not having access to the prior navigation history turns out to be quite annoying for specifically this use case. |
Beta Was this translation helpful? Give feedback.
-
In V6, you can use const location = useLocation(); and check location.key === "default" to do something |
Beta Was this translation helpful? Give feedback.
-
I feel like this is a use case that should be covered by react-router. Also, in addition to determining if the user can go back, what if I need to do the same for going forwards? How do the suggested solutions work in that case? |
Beta Was this translation helpful? Give feedback.
-
As I've tried on {
...,
state: {
"usr": null,
"key": "default",
"idx": 0
}
} Example for go-back function: if (history.state.idx === 0) {
console.log('Cannot go back')
} else {
navigate(-1)
} PS: Please use with caution (I just tested some cases). |
Beta Was this translation helpful? Give feedback.
-
Seems odd for a property like |
Beta Was this translation helpful? Give feedback.
-
Hi
What is the recommended way to check if you can
navigate(-1)
in v6?Say I want to implement a custom back button and disable it when you can't go back.
Beta Was this translation helpful? Give feedback.
All reactions