I'm using nextjs app router. Navigating from products/page.jsx to products/[id]/page.jsx…
- User
I'm using nextjs app router. Navigating from products/page.jsx to products/[id]/page.jsx and then navigating back from products[id]/page.jsx to products/page.jsx should retain the old/first products/page.jsx scroll state... products/page.jsx:
import React from 'react'; import ProductList from '@/components/ProductList'; import AsyncNavBar from '@/components/AsyncNavBar'; import { unstable_cache } from 'next/cache'; const ITEMS_PER_PAGE = 15; export const revalidate = 14400; // 4 hours
const REVALIDATE_SUBBRANDS = 14400; // 4 hours const REVALIDATE_PRODUCTS = 14400; // 4 hours
// Wrap fetchSubBrands with unstable_cache const fetchSubBrands = unstable_cache(async () => { const response = await fetch('https://api.naayiq.com/subcategories/brands', { headers: { 'Content-Type': 'application/json' }, });
if (response.status === 200) { return response.json(); } throw new Error(`Failed to fetch sub-brands: ${response.statusText}`);}, { // Revalidate every 4 hours revalidate: REVALIDATE_SUBBRANDS, });
// Wrap fetchProducts with unstable_cache const fetchProducts = unstable_cache(async () => { const response = await fetch('https://api.naayiq.com/products', { headers: { 'Content-Type': 'application/json' }, });
if (!response.ok) { throw new Error('Failed to fetch products'); } return response.json();}, { // Revalidate every 4 hours revalidate: REVALIDATE_PRODUCTS, });
const getFilteredProducts = async ( page = 1, query = '', c = '', sc = '', b = '', minPriceA = 0, maxPriceA = Infinity, availability = 'all', sortBy = '' ) => { let [productsData, subBrands] = await Promise.all([ fetchProducts(), // Uses unstable_cache b ? fetchSubBrands() : Promise.resolve([]), // Uses unstable_cache if 'b' is truthy ]); let products = productsData.products;
const subCategories = b ? subBrands .filter((item) => item.category_id.toString() === b) .map((item) => item.id.toString()) : []; // Calculate min and max prices let minPrice = Infinity; let maxPrice = -Infinity; products.forEach(product => { product.sizes.forEach(size => { const price = parseFloat(size.price); if (price < minPrice) minPrice = price; if (price > maxPrice) maxPrice = price; }); }); const filterProduct = (product) => { if ( c && !product.categories.some( (cat) => cat.main_category_id?.toString() === c ) ) return false; if ( sc && product?.brand_id.toString() !== sc && !product.categories.some((cat) => cat.id?.toString() === sc) ) return false; if ( b && !subCategories.includes(product?.brand_id.toString()) ) return false; // Price range filter const productPrices = product.sizes.map(size => parseFloat(size.price)); const productMinPrice = Math.min(...productPrices); const productMaxPrice = Math.max(...productPrices); if (productMinPrice < minPriceA || productMaxPrice > maxPriceA) { return false; } if (availability !== 'all') { const inStock = product.sizes.some(size => size.qty > 0); if ( (availability === 'in_stock' && !inStock) || (availability === 'out_of_stock' && inStock) ) { return false; } } if (query) { const normalizedName = product.name .normalize('NFC') .toLowerCase(); const cleanName = normalizedName.replace( /[\u200E\u200F\u202A-\u202E\u2066-\u2069]/g, '' ); const queryWords = query.toLowerCase().split(/\s+/); return queryWords.every((word) => cleanName.includes(word)); } return true; }; // Apply the filter let filteredProducts = products.filter(filterProduct); // Calculate total sold for each product filteredProducts.forEach(product => { product.totalSold = product.sizes.reduce((sum, size) => sum + size.sold, 0); }); // Apply sorting switch (sortBy) { case 'Price: Low to High': filteredProducts.sort((a, b) => Math.min(...a.sizes.map(s => parseFloat(s.price))) - Math.min(...b.sizes.map(s => parseFloat(s.price)))); break; case 'Price: High to Low': filteredProducts.sort((a, b) => Math.max(...b.sizes.map(s => parseFloat(s.price))) - Math.max(...a.sizes.map(s => parseFloat(s.price)))); break; case 'Name: A to Z': filteredProducts.sort((a, b) => a.name.localeCompare(b.name)); break; case 'Name: Z to A': filteredProducts.sort((a, b) => b.name.localeCompare(a.name)); break; case 'Best Selling': filteredProducts.sort((a, b) => b.totalSold - a.totalSold); break; case 'Newest Arrivals': filteredProducts.sort((a, b) => new Date(b.created_at) - new Date(a.created_at)); break; default: // Default sorting (optional) break; } if (query && !sortBy) { const lowerQuery = query.toLowerCase(); filteredProducts.sort((a, b) => { const aIndex = a.name.toLowerCase().indexOf(lowerQuery); const bIndex = b.name.toLowerCase().indexOf(lowerQuery); return ( (aIndex === -1 ? Infinity : aIndex) - (bIndex === -1 ? Infinity : bIndex) ); }); } const totalProducts = filteredProducts.length; const start = 0; const end = page * ITEMS_PER_PAGE; return { products: filteredProducts.slice(start, end), totalProducts, hasMore: end < totalProducts, minPrice, maxPrice, };};
// The main ProductsPage component const ProductsPage = async ({ searchParams }) => { const page = parseInt(searchParams.page) || 1; const query = searchParams.query || ''; const c = searchParams.c || ''; const sc = searchParams.sc || ''; const b = searchParams.b || ''; const minPriceF = parseFloat(searchParams.minPrice) || 0; const maxPriceF = parseFloat(searchParams.maxPrice) || Infinity; const availability = searchParams.availability || 'all'; const sortBy = searchParams.sortBy || ''; const title = searchParams.title || '';
try { const { products, totalProducts, hasMore, minPrice, maxPrice } = await getFilteredProducts( page, query, c, sc, b, minPriceF, maxPriceF, availability, sortBy ); return ( <> <AsyncNavBar /> <ProductList initialProducts={products} totalProducts={totalProducts} hasMore={hasMore} initialPage={page} initialQuery={query} initialC={c} initialSc={sc} initialB={b} minPrice={minPrice} maxPrice={maxPrice} title={sortBy || title || "All Products"} /> </> ); } catch (error) { return <div>Error: {error.message}</div>; }};
export default ProductsPage; ProductList.jsx: 'use client' import React, { useCallback, useEffect, useMemo, useState } from 'react'; import { useRouter, useSearchParams } from 'next/navigation'; import { useInView } from 'react-intersection-observer'; import dynamic from 'next/dynamic'; import ProductItem from './ProductItem'; import ProductLoading from '@/components/ProductLoading'; import NoProductsFound from '@/components/NoProductsFound'; import { usePathname } from 'next/navigation'; import Loading from "./Loading" import {NotificationProvider} from "@/components/NotificationContext";
// Dynamically import the SearchComponent const SearchComponent = dynamic(() => import('@/components/SearchComponent'), { ssr: false, loading: () => , });
// Dynamically import the ProductModal const ProductModal = dynamic(() => import("@/components/ProductDetailModal"), { ssr: false });
export default function ProductList({ initialProducts, hasMore, initialPage, initialQuery, minPrice, maxPrice, title }) { const [products, setProducts] = useState(initialProducts); const [page, setPage] = useState(initialPage); const [loading, setLoading] = useState(false); const [noMoreProducts, setNoMoreProducts] = useState(!hasMore); const [query, setQuery] = useState(initialQuery); const [isNavigating, setIsNavigating] = useState(false);
// New State: Manage the selected product for the modal const [selectedProduct, setSelectedProduct] = useState(null); const { ref, inView } = useInView({ threshold: 0 }); const router = useRouter(); const searchParams = useSearchParams(); const pathname = usePathname(); const loadMoreProducts = useCallback(() => { if (loading || noMoreProducts) return; setLoading(true); const nextPage = page + 1; const params = new URLSearchParams(Array.from(searchParams.entries())); params.set('page', nextPage.toString()); router.push(`/products?${params.toString()}`, { scroll: false }); }, [page, loading, noMoreProducts, searchParams, router]); useEffect(() => { if (inView && !noMoreProducts) { loadMoreProducts(); } }, [inView, loadMoreProducts, noMoreProducts]); const handleSearch = useCallback( (newQuery) => { setQuery(newQuery); const params = new URLSearchParams(Array.from(searchParams.entries())); params.set('query', newQuery); params.set('page', '1'); router.push(`/products?${params.toString()}`, { scroll: false }); }, [searchParams, router] ) useEffect(() => { setProducts(initialProducts); setPage(initialPage); setNoMoreProducts(!hasMore); setQuery(initialQuery); setLoading(false); }, [initialProducts, initialPage, hasMore, initialQuery]); const memoizedProducts = useMemo( () => products.map((product) => ({ ...product, cheapestPrice: getCheapestPrice(product), })), [products] ); const handleProductClick = useCallback( (product) => { setIsNavigating(true); router.push(`/products/${product.id}`, { shallow: true }); }, [router] ); // New Handler: Handle cart button click to open modal const handleCartClick = useCallback( (product) => { setSelectedProduct(product); }, [] ); // New Handler: Close the modal const handleModalClose = useCallback(() => { setSelectedProduct(null); }, []); useEffect(() => { // This effect will run when the pathname changes setIsNavigating(false); }, [pathname]); if (isNavigating) { return <Loading /> } return ( <> <header className="flex mt-24 justify-center items-center mb-8 relative"> <h1 className="text-3xl z-10 text-[#181717] font-sans text-center font-medium"> {title || 'All Products'} </h1> </header> <SearchComponent minPrice={minPrice} maxPrice={maxPrice} query={query} setQuery={handleSearch}/> {memoizedProducts.length > 0 ? ( <div className="grid grid-cols-2 w-full justify-between gap-4 sm:gap-6 ssm3:grid-cols-3 md:grid-cols-4 lg:grid-cols-5"> {memoizedProducts.map((product) => ( <div key={product.id} onClick={() => handleProductClick(product)} className="cursor-pointer" > <ProductItem id={product.id} name={product.name} product={product} handleClick={() => handleProductClick(product)} price={formatPrice(product.cheapestPrice)} imageUrl={product.images[0]} onCartClick={handleCartClick} // Pass the handler /> </div> ))} </div> ) : ( <NoProductsFound /> )} {loading && <ProductLoading />} {!loading && !noMoreProducts && ( <div ref={ref} style={{ height: '20px' }}></div> )} {/* Render Modal Here */} {selectedProduct && ( <NotificationProvider> <ProductModal productData={{ product: selectedProduct }} isOpen={!!selectedProduct} onClose={handleModalClose} /> </NotificationProvider> )} </> );}
const getCheapestPrice = (product) => { const prices = [ product.price && product.price !== '0.00' ? parseFloat(product.price) : Infinity, ...(product.sizes?.map((size) => parseFloat(size.price)) || []), ...(product.colors?.flatMap((color) => [ parseFloat(color.price), ...(color.sizes?.map((size) => parseFloat(size.price)) || []), ]) || []), ].filter((price) => !isNaN(price) && isFinite(price));
return prices.length > 0 ? Math.min(...prices) : null;};
const formatPrice = (price) => { if (price == null || price === Infinity) return 'N/A'; return
${price >= 10000 ? price.toLocaleString() : price} IQD; };const SearchComponentSkeleton = () => ( ); products/[id]/page.jsx: import React, { Suspense } from "react"; import ProductDetail from "@/components/ProductDetail"; import Loading from "@/components/Loading"; import { NotificationProvider } from "@/components/NotificationContext"; export const revalidate = 84600 async function fetchProduct(id) { const response = await fetch(
https://api.naayiq.com/products/${id}, {cache: "force-cache"}); if (!response.ok) { throw new Error('Failed to fetch product'); } return response.json(); }async function ProductContent({ id }) { const { product } = await fetchProduct(id);
return ( <ProductDetail product={product} /> );}
export default function ProductDetailsPage({ params }) { return ( <Suspense fallback={}> ); } ProductDetail.jsx: 'use client'; import React, { useState, useEffect, useCallback } from 'react'; import { ArrowLeft, Minus, Plus } from 'lucide-react'; import Slider from 'react-slick'; import 'slick-carousel/slick/slick.css'; import '@/components/NotificationStyles.css'; import 'slick-carousel/slick/slick-theme.css';
import Image from "next/image"; import { useRouter } from "next/navigation"; import Lightbox from "yet-another-react-lightbox"; import Zoom from "yet-another-react-lightbox/plugins/zoom"; import Fullscreen from "yet-another-react-lightbox/plugins/fullscreen"; import "yet-another-react-lightbox/styles.css"; import { useNotification } from "@/components/NotificationContext"; import Link from "next/link"; import WishlistHeart from "@/components/WishlistHeart"; const formatPrice = (price) => { const formattedPrice = price >= 10000 ? price.toLocaleString('en-US') : price.toString(); return
${formattedPrice} IQD; }; export default function ProductDetail({ product }) { const [selectedColor, setSelectedColor] = useState(null); const [selectedSize, setSelectedSize] = useState(null); const [quantity, setQuantity] = useState(1); const [currentPrice, setCurrentPrice] = useState(product.price); const [lightboxOpen, setLightboxOpen] = useState(false); const [lightboxIndex, setLightboxIndex] = useState(0); const { addNotification } = useNotification(); const [cartItems, setCartItems] = useState([]); const router = useRouter(); const images = product.images.map(img => img.url || img);useEffect(() => { window.scrollTo(0, 0); }, []); const updatePrice = useCallback(() => { let price = product.price; if (selectedSize && selectedSize.price) { price = selectedSize.price; } else if (selectedColor && selectedColor.price) { price = selectedColor.price; } setCurrentPrice(parseFloat(price)); }, [product, selectedColor, selectedSize]); useEffect(() => { const cart = JSON.parse(localStorage.getItem('cart')) || []; setCartItems(cart); // Set initial color and size if available if (product.has_color && product.colors.length > 0) { setSelectedColor(product.colors[0]); } if (product.has_size && product.sizes.length > 0) { setSelectedSize(product.sizes[0]); } updatePrice(); }, []); useEffect(() => { updatePrice(); }, [selectedColor, selectedSize, updatePrice]); const handleColorChange = (color) => { setSelectedColor(color); if (color.sizes && color.sizes.length > 0) { setSelectedSize(color.sizes[0]); } else { setSelectedSize(null); } }; const handleSizeChange = (e) => { const sizeId = parseInt(e.target.value); const newSize = product.sizes.find(size => size.id === sizeId); setSelectedSize(newSize); }; const isInCart = () => { return cartItems.some(item => item.product_id === product.id && item.color_id === selectedColor?.id && item.size_id === selectedSize?.id ); }; const handleAddToCart = () => { const cartItem = { product_id: product.id, color_id: selectedColor?.id, size_id: selectedSize?.id, qty: quantity }; let updatedCart = [...cartItems]; const existingItemIndex = updatedCart.findIndex(item => item.product_id === cartItem.product_id && item.color_id === cartItem.color_id && item.size_id === cartItem.size_id ); if (existingItemIndex > -1) { updatedCart[existingItemIndex].qty += quantity; } else { updatedCart.push(cartItem); } localStorage.setItem('cart', JSON.stringify(updatedCart)); setCartItems(updatedCart); addNotification('success', 'Product Added To Cart'); }; const sliderSettings = { dots: images.length > 1, infinite: false, speed: 500, slidesToShow: 1, slidesToScroll: 1, customPaging: function (i) { return ( <div style={{ width: '12px', height: '12px', background: i === this.currentSlide ? '#695C5C' : '#D9D9D9', borderRadius: '50%', padding: 0, margin: '0 4px' }} /> ); }, }; const lightboxSlides = images.map(src => ({ src: `https://storage.naayiq.com/resources/${src}`}));
// Determine if the product is out of stock const isOutOfStock = (() => { if (product.has_size && selectedSize) { return selectedSize.qty === 0; } else if (product.has_color && selectedColor) { return selectedColor.qty === 0; } else { return product.qty === 0; } })(); return ( <div className="flex overflow-x-hidden font-serif relative z-40 font-medium flex-col -mt-4 -mx-4 bg-white"> <Slider {...sliderSettings} className="w-full mb-2 h-[55vh]"> {images.map((image, index) => ( <div key={index} className="relative w-full h-[60vh]" onClick={() => { setLightboxIndex(index); setLightboxOpen(true); }}> <Image src={`https://storage.naayiq.com/resources/${image}`} alt={`Product image ${index + 1}`} fill={true} unoptimized={true} className="w-full object-cover cursor-pointer" priority={index === 0} /> </div> ))} </Slider> <Lightbox open={lightboxOpen} close={() => setLightboxOpen(false)} index={lightboxIndex} slides={lightboxSlides} plugins={[Zoom, Fullscreen]} carousel={{ finite: images.length <= 1, navigationDisabled: images.length <= 1 }} animation={{ zoom: 500 }} zoom={{ maxZoomPixelRatio: 5, zoomInMultiplier: 2, doubleTapDelay: 300, doubleClickDelay: 300, doubleClickMaxStops: 2, keyboardMoveDistance: 50, wheelZoomDistanceFactor: 100, pinchZoomDistanceFactor: 100, scrollToZoom: true, }} /> <button className="absolute h-12 rounded-[100%] w-12 bg-white-gradient flex justify-center items-center top-4 left-4 z-10" onClick={router.back} > <ArrowLeft width={30} height={30} strokeWidth={1} /> </button> <button className="h-12 rounded-[100%] w-12 absolute top-4 right-4 z-10 bg-white-gradient flex justify-center items-center" > <WishlistHeart product={product} /> </button> <div className="flex-grow bg-white rounded-t-xl shadow-[0px_-4px_8px_3px_rgba(105,92,92,0.1)] p-6 mt-2 relative z-30"> <div className="w-9 h-1 bg-black opacity-70 rounded-full mx-auto mb-6"/> <h1 className="text-xl font-semibold mb-1 capitalize">{product.name}</h1> {isOutOfStock && ( <p className="text-red-500 mt-2 text-lg font-semibold">Out of Stock</p> )} {product.has_color && product.colors.length > 0 && ( <div className="mb-10 mt-6"> <h2 className="text-xl font-medium mb-2">Color</h2> <div className="flex space-x-4 overflow-x-auto pb-2"> {product.colors.map((color) => ( <div key={color.id} className="flex flex-col items-center"> <button className={`w-20 h-20 rounded-full border-2 ${selectedColor?.id === color.id ? 'border-[#3B5345]' : 'border-[#695C5C] border-opacity-50'} mb-2 overflow-hidden`} onClick={() => handleColorChange(color)} disabled={color.qty === 0} > {color.images && color.images.length > 0 && ( <Image src={color.images[0]} alt={color.name} width={80} height={80} className="object-cover" /> )} </button> <span className="text-sm">{color.name}</span> </div> ))} </div> </div> )} {((product.has_size && product.sizes.length > 0) || (selectedColor && selectedColor.sizes && selectedColor.sizes.length > 0)) && ( <div className="mb-6 font-serif"> <select value={selectedSize ? selectedSize.id : ''} onChange={handleSizeChange} className="w-32 p-2 border border-[#E5E7EB] rounded-lg font-serif bg-white" > {(selectedColor && selectedColor.sizes ? selectedColor.sizes : product.sizes).map((size) => ( <option key={size.id} value={size.id} disabled={size.qty === 0}> Size: {size.name} {size.qty === 0 && '(Out of Stock)'} </option> ))} </select> </div> )} <div className="mb-6 pb-28"> <h2 className="text-xl font-semibold w-fit mb-2">Description</h2> <div style={{direction: "rtl"}} className="text-xl mr-2 font-normal text-right font-serif" dangerouslySetInnerHTML={{ __html: product.description.split('\n').map((item, index) => { if (index === 0) { return `<p class="text-xl font-semibold mb-2">${item}</p>`; } else if (item.includes(':')) { return `<p class="text-lg font-semibold mt-4 mb-2">${item}</p>`; } else if (item.trim().startsWith('-')) { return `<li>${item.trim().substring(1)}</li>`; } else { return `<p>${item}</p>`; } }).join('').replace(/(<li>.?<\/li>)+/g, function (match) { return `<ul class="list-disc pl-5 mb-2">${match}</ul>`; }) }} /> </div> <footer className="fixed mt-12 border-[#695C5C]/30 shadow-[0_-4px_6px_-1px_rgba(0,0,0,0.05),0_-2px_4px_-1px_rgba(0,0,0,0.06)] bottom-0 bg-white p-4 right-0 left-0 z-50"> <div className="flex justify-between items-center mb-6"> <span className="text-xl font-serif font-medium">{formatPrice(currentPrice * quantity)}</span> <div className="flex items-center space-x-4"> <button onClick={() => setQuantity(Math.max(1, quantity - 1))} className="w-8 h-8 flex items-center justify-center border border-[#E5E7EB] rounded-full" disabled={isOutOfStock} > <Minus className="w-4 h-4 text-[#3B5345]"/> </button> <span className="text-lg font-medium">{quantity}</span> <button onClick={() => setQuantity(quantity + 1)} className="w-8 h-8 flex items-center justify-center border border-[#E5E7EB] rounded-full" disabled={isOutOfStock} > <Plus className="w-4 h-4 text-[#3B5345]"/> </button> </div> </div> {/* Conditionally render the Add to Cart or Buy Now button based on stock status */} {!isOutOfStock && ( isInCart() ? ( <Link href="/cart" className="w-full font-serif bg-[rgba(59,83,69,0.05)] text-[#3B5345] py-3 rounded-lg font-medium text-lg flex items-center justify-center transition duration-300 border border-[#3B5345]" > <svg className="mr-2" width="29" height="28" viewBox="0 0 29 28" fill="none" xmlns="http://www.w3.org/2000/svg"> <path d="M9.50391 8.94834V7.81668C9.50391 5.19168 11.6156 2.61334 14.2406 2.36834C17.3672 2.06501 20.0039 4.52668 20.0039 7.59501V9.20501" stroke="#3B5345" strokeWidth="1.5" strokeMiterlimit="10" strokeLinecap="round" strokeLinejoin="round"/> <path d="M11.2542 25.6666H18.2542C22.9442 25.6666 23.7842 23.7883 24.0292 21.5016L24.9042 14.5016C25.2192 11.6549 24.4025 9.33325 19.4209 9.33325H10.0875C5.10586 9.33325 4.28919 11.6549 4.60419 14.5016L5.47919 21.5016C5.72419 23.7883 6.56419 25.6666 11.2542 25.6666Z" stroke="#3B5345" strokeWidth="1.5" strokeMiterlimit="10" strokeLinecap="round" strokeLinejoin="round"/> <path d="M18.8318 14.0001H18.8423" stroke="#3B5345" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/> <path d="M10.6638 14.0001H10.6743" stroke="#3B5345" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/> </svg> Buy Now </Link> ) : ( <button onClick={handleAddToCart} className="w-full font-serif bg-[#3B5345] text-white py-3 rounded-lg font-medium text-lg flex items-center justify-center transition duration-300" > <svg className="mr-2" width="29" height="28" viewBox="0 0 29 28" fill="none" xmlns="http://www.w3.org/2000/svg"> <path d="M9.50391 8.94834V7.81668C9.50391 5.19168 11.6156 2.61334 14.2406 2.36834C17.3672 2.06501 20.0039 4.52668 20.0039 7.59501V9.20501" stroke="white" strokeWidth="1.5" strokeMiterlimit="10" strokeLinecap="round" strokeLinejoin="round"/> <path d="M11.2542 25.6666H18.2542C22.9442 25.6666 23.7842 23.7883 24.0292 21.5016L24.9042 14.5016C25.2192 11.6549 24.4025 9.33325 19.4209 9.33325H10.0875C5.10586 9.33325 4.28919 11.6549 4.60419 14.5016L5.47919 21.5016C5.72419 23.7883 6.56419 25.6666 11.2542 25.6666Z" stroke="white" strokeWidth="1.5" strokeMiterlimit="10" strokeLinecap="round" strokeLinejoin="round"/> <path d="M18.8318 14.0001H18.8423" stroke="white" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/> <path d="M10.6638 14.0001H10.6743" stroke="white" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/> </svg> Add To Cart </button> ) )} </footer> </div> </div> );}
- Assistant
To retain the scroll position when navigating between
products/page.jsxandproducts/[id]/page.jsxin your Next.js App Router setup, you need to ensure that the browser's native scroll restoration behavior is leveraged. Here's a comprehensive approach to achieve this:-
Use the
<Link>Component for Navigation:Instead of using
router.pushfor navigation, utilize Next.js's<Link>component. This allows the browser to handle navigation and scroll restoration naturally, preserving the scroll position when navigating back. -
Avoid Conditional Rendering That Resets State:
In your
ProductList.jsx, theisNavigatingstate and the conditional rendering of the<Loading />component can interfere with scroll restoration. Removing these ensures that the scroll state remains unaffected. -
Ensure Scroll Restoration Is Not Disabled:
When using
router.push, avoid setting options that might disable scroll restoration, such as{ scroll: false }, unless it's specifically needed for certain navigations like infinite scrolling. -
Optional: Manually Handle Scroll Positions (If Needed):
If you have complex navigation flows or additional requirements, you might consider manually storing and restoring scroll positions using
sessionStorageor similar methods. However, this is typically unnecessary if you follow the above steps.
Step-by-Step Implementation
1. Update
ProductList.jsxto Use<Link>Replace the
onClickhandler that usesrouter.pushwith Next.js's<Link>component. This allows the browser to handle navigation and scroll restoration naturally.Before:
// Inside ProductList.jsx <div key={product.id} onClick={() => handleProductClick(product)} className="cursor-pointer" > <ProductItem id={product.id} name={product.name} product={product} handleClick={() => handleProductClick(product)} price={formatPrice(product.cheapestPrice)} imageUrl={product.images[0]} onCartClick={handleCartClick} // Pass the handler /> </div>After:
// Inside ProductList.jsx import Link from 'next/link'; // ... other imports <div key={product.id} className="cursor-pointer" > <Link href={`/products/${product.id}`} className="block"> <ProductItem id={product.id} name={product.name} product={product} price={formatPrice(product.cheapestPrice)} imageUrl={product.images[0]} onCartClick={handleCartClick} // Pass the handler /> </Link> </div>Explanation:
-
Wrapping with
<Link>: By wrapping theProductItemwith<Link>, you allow Next.js to handle the navigation. This ensures that when users click on a product, the navigation behaves like a traditional link, preserving scroll positions. -
Removing
onClick: Since<Link>handles the navigation, theonClickhandler that usedrouter.pushis no longer necessary.
2. Remove
isNavigatingState and Conditional RenderingThe
isNavigatingstate and the conditional rendering of the<Loading />component can disrupt the scroll restoration. Removing them ensures that the products list remains mounted and the scroll position is preserved.Before:
// Inside ProductList.jsx const [isNavigating, setIsNavigating] = useState(false); // ... other code const handleProductClick = useCallback( (product) => { setIsNavigating(true); router.push(`/products/${product.id}`, { shallow: true }); }, [router] ); // ... other code if (isNavigating) { return <Loading /> }After:
// Inside ProductList.jsx // Remove the isNavigating state // Remove setIsNavigating and related logic // ... other code // Remove the conditional rendering // if (isNavigating) { // return <Loading /> // }Explanation:
-
State Removal: By removing the
isNavigatingstate and the associatedsetIsNavigatingcalls, you prevent the component from unmounting and remounting during navigation, which can reset scroll positions. -
Conditional Rendering: Eliminating the
<Loading />component ensures that the products list remains present, allowing the scroll position to be preserved naturally.
3. Adjust
router.pushUsage for Infinite ScrollingEnsure that when using
router.pushfor infinite scrolling or other navigations within the same page, you don't disable scroll restoration unless necessary.Before:
// Inside ProductList.jsx const loadMoreProducts = useCallback(() => { if (loading || noMoreProducts) return; setLoading(true); const nextPage = page + 1; const params = new URLSearchParams(Array.from(searchParams.entries())); params.set('page', nextPage.toString()); router.push(`/products?${params.toString()}`, { scroll: false }); }, [page, loading, noMoreProducts, searchParams, router]);After:
// Inside ProductList.jsx const loadMoreProducts = useCallback(() => { if (loading || noMoreProducts) return; setLoading(true); const nextPage = page + 1; const params = new URLSearchParams(Array.from(searchParams.entries())); params.set('page', nextPage.toString()); router.push(`/products?${params.toString()}`); // Remove { scroll: false } }, [page, loading, noMoreProducts, searchParams, router]);Explanation:
- Scroll Restoration: By removing
{ scroll: false }, you allow the browser to handle scroll behavior naturally. However, if you intentionally want to prevent scrolling to the top when loading more products (common in infinite scrolling), you might want to keep this option. In that case, ensure that it doesn't interfere with navigating back from the product detail page.
4. Optional: Manually Handle Scroll Restoration (Advanced)
If, after these changes, you still encounter issues with scroll restoration, you can manually store and restore scroll positions using
sessionStorageorlocalStorage. Here's a basic example usinguseEffect:// Inside ProductList.jsx import { useEffect } from 'react'; // ... inside your component useEffect(() => { // Restore scroll position on mount const scrollY = sessionStorage.getItem('productsScrollY'); if (scrollY) { window.scrollTo(0, parseInt(scrollY, 10)); sessionStorage.removeItem('productsScrollY'); } return () => { // Save scroll position on unmount sessionStorage.setItem('productsScrollY', window.scrollY); }; }, []);Explanation:
-
Storing Scroll Position: When navigating away from the products list, the
useEffectcleanup function saves the currentwindow.scrollYposition tosessionStorage. -
Restoring Scroll Position: When the
ProductListcomponent mounts again, it retrieves the saved scroll position and scrolls the window to that position.
Note: This manual approach is generally unnecessary if using
<Link>for navigation and avoiding conditional unmounting. Use it only if you encounter specific issues that require it.
Final Adjusted
ProductList.jsxHere's how your
ProductList.jsxmight look after applying the suggested changes:'use client' import React, { useCallback, useEffect, useMemo, useState } from 'react'; import Link from 'next/link'; // Import Link import { useRouter, useSearchParams } from 'next/navigation'; import { useInView } from 'react-intersection-observer'; import dynamic from 'next/dynamic'; import ProductItem from './ProductItem'; import ProductLoading from '@/components/ProductLoading'; import NoProductsFound from '@/components/NoProductsFound'; import { usePathname } from 'next/navigation'; import Loading from "./Loading" import { NotificationProvider } from "@/components/NotificationContext"; // Dynamically import the SearchComponent const SearchComponent = dynamic(() => import('@/components/SearchComponent'), { ssr: false, loading: () => <SearchComponentSkeleton />, }); // Dynamically import the ProductModal const ProductModal = dynamic(() => import("@/components/ProductDetailModal"), { ssr: false }); export default function ProductList({ initialProducts, hasMore, initialPage, initialQuery, minPrice, maxPrice, title }) { const [products, setProducts] = useState(initialProducts); const [page, setPage] = useState(initialPage); const [loading, setLoading] = useState(false); const [noMoreProducts, setNoMoreProducts] = useState(!hasMore); const [query, setQuery] = useState(initialQuery); // Remove isNavigating state // const [isNavigating, setIsNavigating] = useState(false); // New State: Manage the selected product for the modal const [selectedProduct, setSelectedProduct] = useState(null); const { ref, inView } = useInView({ threshold: 0 }); const router = useRouter(); const searchParams = useSearchParams(); const pathname = usePathname(); const loadMoreProducts = useCallback(() => { if (loading || noMoreProducts) return; setLoading(true); const nextPage = page + 1; const params = new URLSearchParams(Array.from(searchParams.entries())); params.set('page', nextPage.toString()); router.push(`/products?${params.toString()}`); // Removed { scroll: false } }, [page, loading, noMoreProducts, searchParams, router]); useEffect(() => { if (inView && !noMoreProducts) { loadMoreProducts(); } }, [inView, loadMoreProducts, noMoreProducts]); const handleSearch = useCallback( (newQuery) => { setQuery(newQuery); const params = new URLSearchParams(Array.from(searchParams.entries())); params.set('query', newQuery); params.set('page', '1'); router.push(`/products?${params.toString()}`); // Removed { scroll: false } }, [searchParams, router] ) useEffect(() => { setProducts(initialProducts); setPage(initialPage); setNoMoreProducts(!hasMore); setQuery(initialQuery); setLoading(false); }, [initialProducts, initialPage, hasMore, initialQuery]); const memoizedProducts = useMemo( () => products.map((product) => ({ ...product, cheapestPrice: getCheapestPrice(product), })), [products] ); // Removed handleProductClick // const handleProductClick = useCallback( // (product) => { // setIsNavigating(true); // router.push(`/products/${product.id}`, { shallow: true }); // }, // [router] // ); // New Handler: Handle cart button click to open modal const handleCartClick = useCallback( (product) => { setSelectedProduct(product); }, [] ); // New Handler: Close the modal const handleModalClose = useCallback(() => { setSelectedProduct(null); }, []); useEffect(() => { // This effect will run when the pathname changes // Removed setIsNavigating }, [pathname]); // Removed conditional rendering based on isNavigating // if (isNavigating) { // return <Loading /> // } return ( <> <header className="flex mt-24 justify-center items-center mb-8 relative"> <h1 className="text-3xl z-10 text-[#181717] font-sans text-center font-medium"> {title || 'All Products'} </h1> </header> <SearchComponent minPrice={minPrice} maxPrice={maxPrice} query={query} setQuery={handleSearch} /> {memoizedProducts.length > 0 ? ( <div className="grid grid-cols-2 w-full justify-between gap-4 sm:gap-6 ssm3:grid-cols-3 md:grid-cols-4 lg:grid-cols-5"> {memoizedProducts.map((product) => ( <div key={product.id} className="cursor-pointer" > <Link href={`/products/${product.id}`} className="block"> <ProductItem id={product.id} name={product.name} product={product} price={formatPrice(product.cheapestPrice)} imageUrl={product.images[0]} onCartClick={handleCartClick} // Pass the handler /> </Link> </div> ))} </div> ) : ( <NoProductsFound /> )} {loading && <ProductLoading />} {!loading && !noMoreProducts && ( <div ref={ref} style={{ height: '20px' }}></div> )} {/* Render Modal Here */} {selectedProduct && ( <NotificationProvider> <ProductModal productData={{ product: selectedProduct }} isOpen={!!selectedProduct} onClose={handleModalClose} /> </NotificationProvider> )} </> ); } const getCheapestPrice = (product) => { const prices = [ product.price && product.price !== '0.00' ? parseFloat(product.price) : Infinity, ...(product.sizes?.map((size) => parseFloat(size.price)) || []), ...(product.colors?.flatMap((color) => [ parseFloat(color.price), ...(color.sizes?.map((size) => parseFloat(size.price)) || []), ]) || []), ].filter((price) => !isNaN(price) && isFinite(price)); return prices.length > 0 ? Math.min(...prices) : null; }; const formatPrice = (price) => { if (price == null || price === Infinity) return 'N/A'; return `${price >= 10000 ? price.toLocaleString() : price} IQD`; }; const SearchComponentSkeleton = () => ( <div className="flex mb-4 items-center space-x-2 animate-pulse"> <div className="h-10 bg-gray-200 rounded-md flex-grow"></div> <div className="h-10 w-[5.5rem] bg-gray-200 rounded-md"></div> </div> );4. Verify Scroll Restoration
After making these changes:
-
Navigate to a Product Detail Page:
Click on any product in the
ProductList.jsxto navigate to its detail page. -
Navigate Back:
Use the browser's back button to return to the products list. The scroll position should now be preserved, showing the user exactly where they left off.
Additional Considerations
-
Infinite Scrolling: If you're implementing infinite scrolling, ensure that loading more products doesn't interfere with the scroll restoration. The above adjustments should handle typical infinite scrolling scenarios.
-
Modal Navigation: If you decide to implement modals instead of full page navigations for product details, consider using
next/linkwith modal routes to maintain context. -
Performance: Using
<Link>ensures optimal performance by leveraging Next.js's prefetching capabilities, enhancing the user experience. -
Accessibility: Ensure that the use of
<Link>maintains accessibility standards, such as proper focus management when navigating between pages.
By following these steps, you should achieve the desired behavior of retaining the scroll position when navigating between your products list and product detail pages in a Next.js App Router setup.
-