Paginate: add option to disable history and url param

This commit is contained in:
infinite-persistence 2021-09-10 11:22:54 +08:00
parent 33c52be56c
commit b6f1b00f7d
No known key found for this signature in database
GPG key ID: B9C3252EDC3D0AA0

View file

@ -10,16 +10,18 @@ const PAGINATE_PARAM = 'page';
type Props = {
totalPages: number,
location: { search: string },
history: { push: string => void },
onPageChange?: number => void,
history: { push: (string) => void },
onPageChange?: (number) => void,
disableHistory?: boolean, // Disables the use of '&page=' param and history stack.
};
function Paginate(props: Props) {
const { totalPages = 1, location, history, onPageChange } = props;
const { totalPages = 1, location, history, onPageChange, disableHistory } = props;
const { search } = location;
const [textValue, setTextValue] = React.useState('');
const urlParams = new URLSearchParams(search);
const currentPage = Number(urlParams.get(PAGINATE_PARAM)) || 1;
const initialPage = disableHistory ? 1 : Number(urlParams.get(PAGINATE_PARAM)) || 1;
const [currentPage, setCurrentPage] = React.useState(initialPage);
const isMobile = useIsMobile();
function handleChangePage(newPageNumber: number) {
@ -28,9 +30,13 @@ function Paginate(props: Props) {
}
if (currentPage !== newPageNumber) {
const params = new URLSearchParams(search);
params.set(PAGINATE_PARAM, newPageNumber.toString());
history.push('?' + params.toString());
setCurrentPage(newPageNumber);
if (!disableHistory) {
const params = new URLSearchParams(search);
params.set(PAGINATE_PARAM, newPageNumber.toString());
history.push('?' + params.toString());
}
}
}
@ -58,7 +64,7 @@ function Paginate(props: Props) {
nextClassName="pagination__item pagination__item--next"
breakClassName="pagination__item pagination__item--break"
marginPagesDisplayed={2}
onPageChange={e => handleChangePage(e.selected + 1)}
onPageChange={(e) => handleChangePage(e.selected + 1)}
forcePage={currentPage - 1}
initialPage={currentPage - 1}
containerClassName="pagination"
@ -67,7 +73,7 @@ function Paginate(props: Props) {
{!isMobile && (
<FormField
value={textValue}
onChange={e => setTextValue(e.target.value)}
onChange={(e) => setTextValue(e.target.value)}
className="paginate-channel"
label={__('Go to page:')}
type="text"