How to set current page base on url ?
agoraclx opened this issue · 1 comments
agoraclx commented
Let's say I was typing directly in the URL bar to page 3, how I am supposed to pass this page number to use-pagination? Because it always starts at 1 thanks
jaosn60810 commented
You can use the useEffect hook to call the setPage function when the component mounts. This will let you set the initial page number based on URL or other external parameters.
import React from "react";
import { useParams } from "react-router-dom";
import usePagination from "./usePagination";
const MyComponent = () => {
let { pageNumber } = useParams(); // obtain page number from the URL
pageNumber = parseInt(pageNumber); // ensure it's a number
// initialize the pagination hook
const {
totalPages,
nextPage,
prevPage,
setPage,
firstContentIndex,
lastContentIndex,
page,
gaps,
} = usePagination({
contentPerPage: 10,
count: 100,
});
// set the page number when the component mounts
useEffect(() => {
setPage(pageNumber);
}, []);
// ... rest of your component
};
export default MyComponent;