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

81 lines
1.7 KiB
TypeScript
Raw Normal View History

2020-05-22 14:38:19 +02:00
import React, { ReactElement } from 'react'
2018-09-06 20:27:18 +02:00
import { Link } from 'gatsby'
import styles from './Pagination.module.scss'
2019-11-11 01:00:26 +01:00
import shortid from 'shortid'
2018-09-06 20:27:18 +02:00
2019-11-06 20:44:33 +01:00
const PageNumber = ({
i,
slug,
current
}: {
i: number
slug: string
current?: boolean
}) => {
2019-10-13 19:08:36 +02:00
const classes = current ? styles.current : styles.number
2019-11-06 20:44:33 +01:00
const link = i === 0 ? slug : `${slug}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: {
2019-11-06 20:44:33 +01:00
slug: string
2019-10-02 13:35:50 +02:00
currentPageNumber: number
numPages: number
2019-11-06 20:44:33 +01:00
prevPagePath?: string
nextPagePath?: string
2019-10-02 13:35:50 +02:00
}
2020-05-22 14:38:19 +02:00
}): ReactElement {
2019-11-06 20:44:33 +01:00
const {
slug,
currentPageNumber,
numPages,
prevPagePath,
nextPagePath
} = pageContext
2018-09-29 20:43:10 +02:00
const isFirst = currentPageNumber === 1
const isLast = currentPageNumber === numPages
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) => (
2019-11-11 01:00:26 +01:00
<PageNumber
key={shortid.generate()}
i={i}
slug={slug}
current={currentPageNumber === i + 1}
/>
2018-09-29 20:43:10 +02:00
))}
</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
}