To retain the scroll position when navigating back from a product detail page (/products/[id]) to the products list page (/products), you can complete the TODO by implementing logic that:
- Stores the current scroll position before navigating to the product detail page.
- Retrieves and restores the scroll position when navigating back to the products list.
Here's how you can achieve this:
Step 1: Store Scroll Position Before Navigating
You've partially implemented this in your handleProductClick function by saving the scroll position to sessionStorage. Ensure that this function accurately captures the scroll position before navigation.
const handleProductClick = useCallback(
(product) => {
// Store the current scroll position
sessionStorage.setItem("productsScrollPosition", window.scrollY.toString());
// Navigate to the product detail page
router.push(`/products/${product.id}`, { shallow: true });
},
[router]
);
Explanation:
- Key Naming: Use a specific key like
"productsScrollPosition" to avoid conflicts and make it clear what the value represents.
Step 2: Restore Scroll Position on Mount
Implement the TODO by checking if there's a stored scroll position in sessionStorage when the ProductList component mounts. If it exists, scroll to that position and then remove the stored value to prevent unwanted behavior on subsequent mounts.
useEffect(() => {
// Check if there's a stored scroll position
const storedScrollY = sessionStorage.getItem("productsScrollPosition");
if (storedScrollY !== null) {
// Scroll to the stored position
window.scrollTo(0, parseInt(storedScrollY, 10));
// Remove the stored value
sessionStorage.removeItem("productsScrollPosition");
}
}, []);
Explanation:
- Retrieve Scroll Position: On component mount, retrieve the stored scroll position.
- Scroll to Position: Use
window.scrollTo to restore the scroll.
- Cleanup: Remove the stored value to ensure it's only used once.
Step 3: Enhance Navigation Handling (Optional)
To make the scroll restoration even more reliable, especially if users navigate using browser buttons, you can listen to router events and handle scroll restoration accordingly.
useEffect(() => {
const handleRouteChange = (url) => {
if (url.includes("/products")) {
const storedScrollY = sessionStorage.getItem("productsScrollPosition");
if (storedScrollY !== null) {
window.scrollTo(0, parseInt(storedScrollY, 10));
sessionStorage.removeItem("productsScrollPosition");
}
}
};
router.events.on("routeChangeComplete", handleRouteChange);
return () => {
router.events.off("routeChangeComplete", handleRouteChange);
};
}, [router.events]);
Explanation:
- Router Events: Listen to
routeChangeComplete to detect when navigation has finished.
- Conditional Restoration: Only restore scroll if navigating back to the
/products page.
- Cleanup: Remove the event listener when the component unmounts.
Complete Implementation
Integrating the above steps into your ProductList component:
'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 components
const SearchComponent = dynamic(() => import('@/components/SearchComponent'), {
ssr: false,
loading: () => <SearchComponentSkeleton />,
});
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);
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) => {
// Store the current scroll position
sessionStorage.setItem("productsScrollPosition", window.scrollY.toString());
// Navigate to the product detail page
router.push(`/products/${product.id}`, { shallow: true });
},
[router]
);
// Restore scroll position on mount
useEffect(() => {
const storedScrollY = sessionStorage.getItem("productsScrollPosition");
if (storedScrollY !== null) {
window.scrollTo(0, parseInt(storedScrollY, 10));
sessionStorage.removeItem("productsScrollPosition");
}
}, []);
// Optional: Handle browser navigation (back/forward buttons)
useEffect(() => {
const handleRouteChange = (url) => {
if (url === '/products' || url.startsWith('/products?')) {
const storedScrollY = sessionStorage.getItem("productsScrollPosition");
if (storedScrollY !== null) {
window.scrollTo(0, parseInt(storedScrollY, 10));
sessionStorage.removeItem("productsScrollPosition");
}
}
};
router.events.on("routeChangeComplete", handleRouteChange);
return () => {
router.events.off("routeChangeComplete", handleRouteChange);
};
}, [router.events]);
// Handler for cart button click to open modal
const handleCartClick = useCallback(
(product) => {
setSelectedProduct(product);
},
[]
);
// Handler to 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 = () => (
<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>
);
Additional Recommendations
-
Debounce Scroll Restoration:
If you notice any jitteriness or rapid scroll changes, consider debouncing the window.scrollTo function to ensure smooth restoration.
-
Use useLayoutEffect for Synchronous Execution:
In cases where you need the scroll to be restored before the browser paints, consider using useLayoutEffect instead of useEffect. This can prevent flickering.
useLayoutEffect(() => {
const storedScrollY = sessionStorage.getItem("productsScrollPosition");
if (storedScrollY !== null) {
window.scrollTo(0, parseInt(storedScrollY, 10));
sessionStorage.removeItem("productsScrollPosition");
}
}, []);
Note: useLayoutEffect runs synchronously after all DOM mutations. Ensure that this doesn't lead to performance issues, especially if the scroll restoration is heavy.
-
Fallback for No JavaScript:
If your application needs to support scenarios where JavaScript is disabled, consider implementing server-side solutions or using anchor links for scroll restoration.
-
Handling Multiple Scroll Positions:
If your application has multiple list pages or complex navigation patterns, consider storing scroll positions based on unique keys (e.g., route paths) to ensure accurate restoration.
Alternative Approach: Browser's Native Scroll Restoration
Modern browsers offer native scroll restoration via the History API. You can leverage this to simplify your implementation.
useEffect(() => {
if ('scrollRestoration' in window.history) {
window.history.scrollRestoration = 'manual';
}
const handleRouteChangeComplete = () => {
const storedScrollY = sessionStorage.getItem("productsScrollPosition");
if (storedScrollY !== null) {
window.scrollTo(0, parseInt(storedScrollY, 10));
sessionStorage.removeItem("productsScrollPosition");
}
};
router.events.on('routeChangeComplete', handleRouteChangeComplete);
return () => {
router.events.off('routeChangeComplete', handleRouteChangeComplete);
};
}, [router.events]);
Pros:
- Utilizes the browser's native capabilities.
- Reduces manual handling of scroll positions.
Cons:
- Less control over the exact timing and behavior.
- Browser compatibility considerations.
Conclusion
By completing the TODO with the provided implementation, your application will effectively retain and restore the scroll position when navigating between the products list and product detail pages. This enhances the user experience by maintaining their place in the product list, especially during infinite scrolling scenarios.
Feel free to adjust the key names and storage mechanisms (sessionStorage vs. localStorage) based on your application's specific requirements.