概要
目次
検索結果の2ページ目を表示できるよう実装します。
以下gifアニメは実装後の様子です。
開発環境
OS:Windows10
IDE:VSCode
"@next/font": "13.1.5",
"autoprefixer": "10.4.14",
"eslint": "8.39.0",
"eslint-config-next": "13.3.1",
"next": "13.3.1",
"postcss": "8.4.23",
"react": "18.2.0",
"react-dom": "18.2.0",
"react-icons": "^4.8.0",
"tailwindcss": "3.3.2"
実装のポイント
APIのパラメーターstartを追加します。
1ページあたり10件表示するようにします。
Start=1 最初の1ページ目
Nextを押したときの処理
Start=11 2ページ目の場合
2ページからは前のページに進めるリンクを表示します。
Previousを押したときの処理
justify-betweenでPreviousとNextを配置
コード部分
PaginationButtons
PaginationButtons.jsx
"use client"
import Link from "next/link";
import {usePathname,useSearchParams} from "next/navigation";
import { BsChevronLeft,BsChevronRight } from "react-icons/bs";
export default function PaginationButton(){
const pathname = usePathname();
const searchParams = useSearchParams();
const searchTerm = searchParams.get("searchTerm");
const startIndex = +searchParams.get("start") || 1;
return(
<div className="text-blue-700 flex px-10 pb-4 justify-between sm:justify-start sm:space-x-44 sm:px-0">
{startIndex >= 10 && (
<Link href={`${pathname}?searchTerm=${searchTerm}&start=${startIndex - 10}`}>
<div className="flex flex-col cursor-pointer items-center hover:underline">
<BsChevronLeft clssName="h-5" />
<p>Previous</p>
</div>
</Link>
)}
{startIndex <= 90 && (
<Link
href={`${pathname}?searchTerm=${searchTerm}&start=${startIndex + 10}`}
>
<div className="flex flex-col cursor-pointer items-center hover:underline">
<BsChevronRight className="h-5" />
<p>Next</p>
</div>
</Link>
)}
</div>
)
}
WebSearchResults
WebSearchResults.jsx
import Link from "next/link";
import Parser from "html-react-parser";
import PaginationButtons from "./PaginationButtons";
export default function WebSearchResults({results}){
return(
<div className="w-full mx-auto px-3 pb-24 sm:pl-[5%] md:pl-[14%] lg:pl-52">
<p className="text-gray-600 text-sm mb-5 mt-3">
About {results.searchInformation?.formattedTotalResults}
results ({results.searchInformation?.formattedSearchTime} seconds)
</p>
{results.items?.map((result) => (
<div className="mb-8 max-w-xl" key={result.link}>
<div className="group flex flex-col">
<Link className="text-sm truncate" href={result.link}>
{result.formattedUrl}
</Link>
<Link className="group-hover:underline decoration-blue-800 text-xl truncate font-medium text-blue-900" href={result.link}>
{result.title}
</Link>
<p className="text-gray-600">
{Parser(result.htmlSnippet)}
</p>
</div>
</div>
))}
<div className="ml-16">
+ <PaginationButtons />
</div>
</div>
)
}
参考
css
その他
Next.js usePathname()
Next.js useSearchParams()
Udemy
githubコミット分