Add pagination support (#52)

* Add pagination support

* Change posts per page value to 10

* Change /blog/1 page to be same as /blog/
Modify canonical url to reflect current page

* Conditionally render pagination component
This commit is contained in:
Ahmad Al Maaz
2021-05-26 16:56:19 +03:00
committed by GitHub
parent 3c3cb9cbeb
commit 847f2537c3
5 changed files with 9439 additions and 21 deletions

54
pages/blog/page/[page].js Normal file
View File

@ -0,0 +1,54 @@
import { PageSeo } from '@/components/SEO'
import siteMetadata from '@/data/siteMetadata'
import { getAllFilesFrontMatter } from '@/lib/mdx'
import ListLayout from '@/layouts/ListLayout'
import { POSTS_PER_PAGE } from '../../blog'
export async function getStaticPaths() {
const totalPosts = await getAllFilesFrontMatter('blog')
const totalPages = Math.ceil(totalPosts.length / POSTS_PER_PAGE)
const paths = Array.from({ length: totalPages }, (_, i) => ({
params: { page: '' + (i + 1) },
}))
return {
paths,
fallback: false,
}
}
export async function getStaticProps(context) {
const {
params: { page },
} = context
const getPosts = await getAllFilesFrontMatter('blog')
const pageNumber = parseInt(page)
const postsPerPage = getPosts.slice(
POSTS_PER_PAGE * (pageNumber - 1),
POSTS_PER_PAGE * pageNumber
)
const pagination = {
currentPage: pageNumber,
totalPages: Math.ceil(getPosts.length / POSTS_PER_PAGE),
}
return {
props: {
postsPerPage,
pagination,
},
}
}
export default function PostPage({ postsPerPage, pagination }) {
return (
<>
<PageSeo
title={siteMetadata.title}
description={siteMetadata.description}
url={`${siteMetadata.siteUrl}/blog/${pagination.currentPage}`}
/>
<ListLayout posts={postsPerPage} pagination={pagination} title="All Posts" />
</>
)
}