1
0
Fork 0
blog/src/components/molecules/Pagination.tsx

67 lines
1.6 KiB
TypeScript
Raw Normal View History

2018-09-06 20:27:18 +02:00
import React from 'react'
import { Link } from 'gatsby'
2019-10-13 19:08:36 +02:00
import shortid from 'shortid'
2018-09-06 20:27:18 +02:00
import styles from './Pagination.module.scss'
2019-10-13 19:08:36 +02:00
function PageNumber({ i, current }: { i: number; current?: boolean }) {
const classes = current ? styles.current : styles.number
const link = i === 0 ? '' : `/page/${i + 1}`
2018-09-29 20:43:10 +02:00
2019-10-13 19:08:36 +02:00
return (
<Link className={classes} to={link}>
{i + 1}
</Link>
)
}
function PrevNext({
2019-10-02 13:35:50 +02:00
prevPagePath,
nextPagePath
}: {
prevPagePath?: string
nextPagePath?: string
2019-10-13 19:08:36 +02:00
}) {
2018-09-29 20:43:10 +02:00
const link = prevPagePath || nextPagePath
const rel = prevPagePath ? 'prev' : 'next'
const title = prevPagePath ? 'Newer Posts' : 'Older Posts'
2018-09-06 20:27:18 +02:00
return (
2018-09-29 20:43:10 +02:00
<Link to={link} rel={rel} title={title}>
{prevPagePath ? '←' : '→'}
</Link>
)
}
2019-10-02 13:35:50 +02:00
export default function Pagination({
pageContext
}: {
pageContext: {
currentPageNumber: number
numPages: number
prevPage?: number
nextPage?: number
}
}) {
2018-09-29 20:43:10 +02:00
const { currentPageNumber, numPages, prevPage, nextPage } = pageContext
const isFirst = currentPageNumber === 1
const isLast = currentPageNumber === numPages
const prevPagePath = currentPageNumber === 2 ? '/' : `/page/${prevPage}`
const nextPagePath = `/page/${nextPage}`
2019-10-13 19:08:36 +02:00
return (
2018-09-06 20:27:18 +02:00
<div className={styles.pagination}>
2018-09-29 20:43:10 +02:00
<div>{!isFirst && <PrevNext prevPagePath={prevPagePath} />}</div>
<div>
{Array.from({ length: numPages }, (_, i) => (
<PageNumber
2019-10-13 19:08:36 +02:00
key={shortid.generate()}
2018-09-29 20:43:10 +02:00
i={i}
current={currentPageNumber === i + 1}
/>
))}
</div>
<div>{!isLast && <PrevNext nextPagePath={nextPagePath} />}</div>
2018-09-06 20:27:18 +02:00
</div>
2019-10-13 19:08:36 +02:00
)
2018-09-06 20:27:18 +02:00
}