概要
目次
今回は I`m Feeling Lucky機能を追加します。
I`m Feeling Luckyはランダムな検索結果を表示する機能です。
以下画像はI`m Feeling Luckyを実行したときの結果です。URLにランダムな文字が入っていることを確認できます。(ページ自体は現時点では未実装)
開発環境
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"
実装のポイント
RandomAPIからデータを取得する
RandomAPIから取得した文字をNext.jsのuseRouteを使ってURLのパラメーターに渡します。
ボタンのレイアウト
ディスプレイサイズ640px 以下
ディスプレイサイズ640px 以上
コード部分
HomeSearch
HomeSearch.jsx
"use client"
import {AiOutlineSearch} from "react-icons/ai";
import {BsFillMicFill} from "react-icons/bs";
import { useRouter } from "next/navigation";
import { useState } from "react";
export default function HomeSearch() {
const router = useRouter();
const[input, setInput] = useState("");
function handleSubmit(e){
e.preventDefault();
if(!input.trim()) return;
router.push(`/search/web?_searchTerm=${input}`);
}
+ async function randomSearch(){
+ const response = await fetch("https://random-word-api.herokuapp.com/word")
+ .then((res) => res.json())
+ .then((data) => data[0]);
+ if(!response) return;
+ router.push(`/search/web?searchTerm=${response}`);
+ }
return (
<>
<form onSubmit={handleSubmit} className="flex w-full mt-5 mx-auto max-w-[90%] border border-gray-200 px-5 py-3 rounded-full hover:shadow-md focus-within:shadow-md transition-shadow sm:max-w-xl lg:max-w-2xl">
<AiOutlineSearch className="text-xl text-gray-500 mr-3" />
<input type="text" className="flex-grow focus:outline-none" onChange={(e) => setInput(e.target.value)} value={input}/>
<BsFillMicFill className="text-lg"/>
</form>
<div className="flex flex-col space-y-2 sm:space-y-0 sm:space-x-4 justify-center sm:flex-row mt-8">
+ <button onClick={handleSubmit} className="btn">
Google Search
</button>
+ <button onClick={randomSearch} className="btn flex items-center justify-center disabled:opacity-80">
+ I am Feeling Lucky
+ </button>
</div>
</>
)
}
参考
Random word API
Udemy
githubコミット分