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

77 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'
2020-07-19 13:31:27 +02:00
import { PageContext } from '../../@types/Post'
import Icon from '../atoms/Icon'
2021-03-14 01:34:04 +01:00
import {
current as styleCurrent,
2021-03-14 01:54:16 +01:00
number as styleNumber,
2021-03-14 01:34:04 +01:00
pagination
} from './Pagination.module.css'
2018-09-06 20:27:18 +02:00
2021-03-15 21:01:55 +01:00
function PageNumber({
2019-11-06 20:44:33 +01:00
i,
slug,
current
}: {
i: number
slug: string
current?: boolean
2021-03-15 21:01:55 +01:00
}): JSX.Element {
2021-03-14 01:54:16 +01:00
const classes = current ? styleCurrent : styleNumber
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
2021-03-15 21:01:55 +01:00
}): JSX.Element {
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 (
2021-03-14 01:54:16 +01:00
<Link to={link} rel={rel} title={title} className={styleNumber}>
2020-07-19 13:31:27 +02:00
{prevPagePath ? (
<Icon name="ChevronLeft" />
) : (
<Icon name="ChevronRight" />
)}
2018-09-29 20:43:10 +02:00
</Link>
)
}
2019-10-02 13:35:50 +02:00
export default function Pagination({
pageContext
}: {
2020-07-19 13:31:27 +02:00
pageContext: PageContext
2020-05-22 14:38:19 +02:00
}): ReactElement {
2021-05-23 13:38:15 +02: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 (
2021-03-14 01:34:04 +01:00
<div className={pagination}>
2020-07-19 13:31:27 +02:00
{!isFirst && <PrevNext prevPagePath={prevPagePath} />}
{Array.from({ length: numPages }, (_, i) => (
<PageNumber
2022-05-12 01:00:19 +02:00
key={i}
2020-07-19 13:31:27 +02:00
i={i}
slug={slug}
current={currentPageNumber === i + 1}
/>
))}
{!isLast && <PrevNext nextPagePath={nextPagePath} />}
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
}