2021-08-19
Next.js + TailwindCSS でページネーション実装
一旦文章なし
実装
import Link from 'next/link';
export const Pagination = ({ maxPageNumber, currentPageNumber }) => {
currentPageNumber = Number(currentPageNumber);
maxPageNumber = Number(maxPageNumber);
const prevPage = currentPageNumber - 1;
const nextPage = currentPageNumber + 1;
return (
<div className="flex px-3 my-12">
{currentPageNumber !== 1 && (
<Link href={`/blogs/page/${prevPage}`}>
<a>< Previous</a>
</Link>
)}
{currentPageNumber !== maxPageNumber && (
<Link href={`/blogs/page/${nextPage}`}>
<a className="ml-4">Next ></a>
</Link>
)}
</div>
);
};
import Image from 'next/image';
import Blog from '../components/Blog';
import { client } from '../libs/client';
import { Pagination } from '../components/Pagination';
export default function Home({ blog, totalCount }) {
return (
<Layout title="Home">
<p className="text-4xl m-10">blog一覧</p>
<Blog blog={blog} />
<Pagination currentPageNumber={1} maxPageNumber={Math.ceil(totalCount / 4)} />
</Layout>
);
}
export const getStaticProps = async () => {
const offset = 0;
const limit = 4;
const queries = { offset: offset, limit: limit };
const data = await client.get({ endpoint: 'blogs', queries: queries });
return {
props: {
blog: data.contents,
totalCount: data.totalCount,
},
};
};
import { client } from '../../../libs/client';
import Layout from '../../../components/Layout';
import Blog from '../../../components/Blog';
import { Pagination } from '../../../components/Pagination';
export default function BlogPageId({ blog, totalCount, currentPageNumber }) {
return (
<Layout title="blogpage">
<Blog blog={blog} />
<Pagination currentPageNumber={currentPageNumber} maxPageNumber={Math.ceil(totalCount / 4)} />
</Layout>
);
}
export const getStaticPaths = async () => {
const range = (start, end) => [...Array(end - start + 1)].map((_, i) => start + i);
const data = await client.get({ endpoint: 'blogs' });
const { totalCount } = data;
const paths = range(1, Math.ceil(totalCount / 4)).map((i) => `/blogs/page/${i}`);
return { paths, fallback: false };
};
export const getStaticProps = async (context) => {
const numId = context.params.id;
const offset = (numId - 1) * 4;
const limit = 4;
const queries = { offset: offset, limit: limit };
const data = await client.get({ endpoint: 'blogs', queries: queries });
return {
props: {
blog: data.contents,
totalCount: data.totalCount,
currentPageNumber: numId,
},
};
};