, а затем нажать кнопку Brower Back. Из -за этого восстановление прокрутки происходит до того, как список полностью отображается, поэтому прокрутка прыгает в верхнюю часть, а не оставаться на предыдущей позиции.
Использование window.history.scrollrestoration = "Manual". Компонент прокрутки.// src/main.jsx
import React from "react";
import "./index.css";
import ReactDOM from "react-dom/client";
import { BrowserRouter } from "react-router-dom";
import App from "./App";
import SmartScroll from './utils/SmartScroll';
import { CartProvider } from "./context/CartContext";
import { WishlistProvider } from "./context/WishlistContext";
import { AuthProvider } from "./context/AuthContext";
import { SearchProvider } from "./context/SearchContext";
import { FilterProvider } from "./context/FilterContext";
ReactDOM.createRoot(document.getElementById("root")).render(
);
< /code>
// src/App/jsx
import { Routes, Route } from "react-router-dom";
import Home from "./pages/Home/Home";
import Cart from "./pages/Cart";
import CarDetails from './pages/CarDetails';
import Navbar from "./components/layout/Navbar";
import Footer from "./components/layout/Footer";
import Checkout from "./pages/Checkout";
import Wishlist from "./pages/Wishlist";
import Login from "./pages/Login";
import Signup from "./pages/Signup";
import Success from "./pages/Success";
import About from "./pages/About";
import MyOrders from "./pages/MyOrders";
import ReceiptPage from "./pages/ReceiptPage";
import Inventory from "./pages/Inventory";
import SellYourCar from "./pages/Sellcar";
import Profile from "./pages/Profile";
import EditProfile from "./pages/EditProfile";
import SuccessSold from "./pages/SuccessSold";
import Sold from "./pages/Sold";
import { SoldProvider } from "./context/SoldContext";
function App() {
return (
{/* Public Routes */}
{/* Protected Routes */}
);
}
export default App;
< /code>
import { useLayoutEffect, useRef } from "react";
import { useLocation, useNavigationType } from "react-router-dom";
function getScroller() {
return document.scrollingElement || document.documentElement;
}
export default function SmartScroll({ ready = true }) {
const location = useLocation();
const navType = useNavigationType();
const restored = useRef(false);
useLayoutEffect(() => {
if ("scrollRestoration" in window.history) {
window.history.scrollRestoration = "manual";
}
const scroller = getScroller();
const key = `scroll:${location.key}`;
const restoreScroll = () => {
const saved = sessionStorage.getItem(key);
if (saved) {
const { x = 0, y = 0 } = JSON.parse(saved);
scroller.scrollTo({ left: x, top: y, behavior: "auto" });
restored.current = true;
}
};
if (navType === "POP") {
// Wait until content is ready
if (ready) {
restoreScroll();
} else {
const interval = setInterval(() => {
if (ready && !restored.current) {
restoreScroll();
clearInterval(interval);
}
}, 50);
return () => clearInterval(interval);
}
} else {
// New page → scroll to top
scroller.scrollTo({ left: 0, top: 0, behavior: "auto" });
}
// Save scroll on unmount
return () => {
const s = getScroller();
sessionStorage.setItem(key, JSON.stringify({ x: s.scrollLeft, y: s.scrollTop }));
};
}, [location, navType, ready]);
return null;
}
< /code>
import { useEffect, useState, useLayoutEffect, useRef } from "react";
import { collectionGroup, getDocs, query } from "firebase/firestore";
import { db } from "../../firebase/firebase";
import CarCard from "../../components/cars/CarCard";
import Cambodia from "../../assets/images/logo/Cambodia.png";
export default function CarList({ filters = {}, sortOption }) {
const [cars, setCars] = useState([]);
const [carsToDisplay, setCarsToDisplay] = useState(12);
const containerRef = useRef(null); // New: ref for car grid container
// Fetch cars
useEffect(() => {
const fetchCars = async () => {
const savedCars = sessionStorage.getItem("carsList");
if (savedCars) {
setCars(JSON.parse(savedCars));
return;
}
const carsCollection = collectionGroup(db, "cars");
const q = query(carsCollection);
const querySnapshot = await getDocs(q);
const fetchedCars = querySnapshot.docs.map((doc) => ({ id: doc.id, ...doc.data() }));
const shuffledCars = fetchedCars.sort(() => Math.random() - 0.5);
setCars(shuffledCars);
sessionStorage.setItem("carsList", JSON.stringify(shuffledCars));
};
fetchCars();
}, []);
const filterAndSortCars = () => {
let result = [...cars];
const { brand, condition, location, price, search, type, year } = filters;
result = result.filter((car) => {
const matchesSearch =
!search || `${car.name} ${car.model}`.toLowerCase().includes(search.toLowerCase());
const matchesLocation = location === "All locations" || car.location === location;
const matchesBrand = brand === "All brands" || car.name === brand;
const matchesType = type === "All types" || car.type === type;
const matchesCondition = condition === "All conditions" || car.condition === condition;
const matchesYear = year === "All years" || car.year === year;
const matchesPrice =
price === "No max" || (price && car.price a.price - b.price);
case "price-desc":
return result.sort((a, b) => b.price - a.price);
case "year-desc":
return result.sort((a, b) => b.year - a.year);
case "year-asc":
return result.sort((a, b) => a.year - b.year);
default:
return result;
}
};
const filteredCars = filterAndSortCars();
const carsToShow = filteredCars.slice(0, carsToDisplay);
const handleViewMore = () => setCarsToDisplay((prev) => prev + 8);
//
useLayoutEffect(() => {
const key = "cars-scroll"; // fixed key for CarList
const scroller = document.scrollingElement || document.documentElement;
const restoreScroll = () => {
const saved = sessionStorage.getItem(key);
if (saved) {
const { x = 0, y = 0 } = JSON.parse(saved);
scroller.scrollTo({ left: x, top: y, behavior: "auto" });
}
};
// Only restore when grid has been painted
if (cars.length > 0) {
restoreScroll();
}
return () => {
sessionStorage.setItem(
key,
JSON.stringify({ x: scroller.scrollLeft, y: scroller.scrollTop })
);
};
}, [cars]);
return (
Cars for Sale
{carsToShow.length > 0
? carsToShow.map((car) => )
: (
No cars found matching your criteria.
Try adjusting your filters or search query.
)}
{filteredCars.length > carsToDisplay && (
View More
)}
);
}
Подробнее здесь: https://stackoverflow.com/questions/797 ... namic-list
Мобильная версия