From 1df12cc8b7bdbaaba115d6a98c347d82017dc6f3 Mon Sep 17 00:00:00 2001 From: Piyush Waghela Date: Mon, 25 Nov 2024 15:19:37 +0530 Subject: [PATCH 1/3] fix: preserve scroll position on navbar back button Updates navbar back navigation to maintain scroll position when returning to previous page. Prevents unwanted scroll reset and improves UX. Add scroll position tracking Modify back button handler Implement position restoration --- src/components/Navbar.tsx | 38 ++++++++++++++++++++++++++++++++++---- 1 file changed, 34 insertions(+), 4 deletions(-) diff --git a/src/components/Navbar.tsx b/src/components/Navbar.tsx index 052a855c5..528fe1246 100644 --- a/src/components/Navbar.tsx +++ b/src/components/Navbar.tsx @@ -3,7 +3,7 @@ import { motion, AnimatePresence } from 'framer-motion'; import { useSession } from 'next-auth/react'; import { usePathname, useRouter } from 'next/navigation'; -import React, { useState, useCallback, useMemo } from 'react'; +import React, { useState, useCallback, useMemo, useEffect } from 'react'; import Link from 'next/link'; import { ArrowLeft, Menu, Search, X } from 'lucide-react'; import { Button } from './ui/button'; @@ -12,6 +12,8 @@ import ThemeToggler from './ThemeToggler'; import ProfileDropdown from './profile-menu/ProfileDropdown'; import { SearchBar } from './search/SearchBar'; +const scrollPositions = new Map(); + export const Navbar = () => { const { data: session } = useSession(); const router = useRouter(); @@ -40,6 +42,34 @@ export const Navbar = () => { [], ); + // Save scroll position when leaving a page + + useEffect(() => { + const handleScroll = () => { + scrollPositions.set(pathname, window.scrollY); + }; + + window.addEventListener('scroll', handleScroll); + + return () => window.removeEventListener('scroll', handleScroll); + }, [pathname]); + + // Custom back navigation with scroll position restoration + + const handleBack = useCallback(() => { + scrollPositions.set(pathname, window.scrollY); + + // Use window.history to go back + window.history.back(); + + // Restore scroll position after a short delay to ensure the page has loaded + setTimeout(() => { + const previousPath = window.location.pathname; + const savedPosition = scrollPositions.get(previousPath) || 0; + window.scrollTo(0, savedPosition); + }, 100); + }, [pathname]); + return ( <> { > {session?.user && pathname !== '/home' && (