Using router.back() with fallback to root when no previous page #74685
Replies: 2 comments 4 replies
-
In this case, when looking to maintain the functionality of the back button, the conditions stipulated can also be fulfilled by implementing a logic that checks the presence of the entry in the history. If there is no history entry or the user has opened the page directly, we have to manage the redirection to the root page of the site ( 'use client';
import { useRouter } from 'next/router';
import { useCallback } from 'react';
export default function BackButton() {
const router = useRouter();
const handleBack = useCallback(() => {
// Check if there is a history entry
if (window.history.state && window.history.state.idx > 0) {
// Use router.back() to navigate back
router.back();
} else {
// Redirect to root if no previous page
router.push('https://shop.com');
}
}, [router]);
return (
<button onClick={handleBack}>
Back
</button>
);
} |
Beta Was this translation helpful? Give feedback.
-
I think the idea of using Maybe... you could Yet another reason to not rely on idx I guess. They did suggest tracking this yourself, on an in-memory stack, or in session storage perhaps? |
Beta Was this translation helpful? Give feedback.
-
Let's assume our domain is https://shop.com
I'm implementing a custom back button and want to achieve the following behavior:
When a user clicks my custom back button (not the browser's back button):
Example scenarios:
Current implementation using router.back() doesn't handle these cases properly. What's the recommended way to implement this behavior?
Here's my current component:
Beta Was this translation helpful? Give feedback.
All reactions