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