Nextjs detect previous route

Is there a way to detect if the user is going back to a previous page? Right now I am doing this which does not work always, seems like it does not work for nested routes not sure if there is a good solution
export default function MainLayout({ children }: Props) {
const router = useRouter()
const [sidebarOpen, setSidebarOpen] = useState(false)
// save current route to determine if we are going back or forward
const [currentRoute, setCurrentRoute] = useState(router.route)

// check if we are going back or forward
router.events.on('routeChangeStart', (url) => {
if (url === currentRoute) {
setCurrentRoute(url)
}
})

const getMotion = () => {
// if going back to previous page, use left slide
if (currentRoute === router.route) {
return (
<LeftSlideMotion className="mun-h-screen">{children}</LeftSlideMotion>
)
}

return (
<RightSlideMotion className="min-h-screen">{children}</RightSlideMotion>
)
}
export default function MainLayout({ children }: Props) {
const router = useRouter()
const [sidebarOpen, setSidebarOpen] = useState(false)
// save current route to determine if we are going back or forward
const [currentRoute, setCurrentRoute] = useState(router.route)

// check if we are going back or forward
router.events.on('routeChangeStart', (url) => {
if (url === currentRoute) {
setCurrentRoute(url)
}
})

const getMotion = () => {
// if going back to previous page, use left slide
if (currentRoute === router.route) {
return (
<LeftSlideMotion className="mun-h-screen">{children}</LeftSlideMotion>
)
}

return (
<RightSlideMotion className="min-h-screen">{children}</RightSlideMotion>
)
}
4 Replies
Unknown User
Unknown User2y ago
Message Not Public
Sign In & Join Server To View
utdev
utdev2y ago
Using nextjs 12
Neto
Neto2y ago
GitHub
GitHub - STNeto1/next-history: next-history
next-history. Contribute to STNeto1/next-history development by creating an account on GitHub.
Neto
Neto2y ago
small demo with a poc you can interact with local storage to record between session
Want results from more Discord servers?
Add your server