From 0de1799c53926e33d846cc58dd5272d9b96247c3 Mon Sep 17 00:00:00 2001 From: Piyush Waghela Date: Thu, 28 Nov 2024 22:14:14 +0530 Subject: [PATCH] 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 | 43 +++++++++++++++++++++++++++++++++------ 1 file changed, 37 insertions(+), 6 deletions(-) diff --git a/src/components/Navbar.tsx b/src/components/Navbar.tsx index 052a855c5..b4e102779 100644 --- a/src/components/Navbar.tsx +++ b/src/components/Navbar.tsx @@ -2,8 +2,8 @@ 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 { usePathname } from 'next/navigation'; +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,9 +12,13 @@ import ThemeToggler from './ThemeToggler'; import ProfileDropdown from './profile-menu/ProfileDropdown'; import { SearchBar } from './search/SearchBar'; +//global map data structure to store scroll position + +const scrollPositions = new Map(); + export const Navbar = () => { const { data: session } = useSession(); - const router = useRouter(); + const [isMenuOpen, setIsMenuOpen] = useState(false); const [isSearchOpen, setIsSearchOpen] = useState(false); const pathname = usePathname(); @@ -40,6 +44,33 @@ 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' && (