はじめに
ポケモンの一覧ページと詳細ページを行き来できるようにするために、React Routerを導入します。
本記事では、ルーティングの基本的な設定方法と、選択したポケモンの詳細ページへ遷移する実装を行います。
次のページのポケモンを検索するボタンを作成
App.js
import { useEffect, useState } from 'react';
import './App.css';
import { getAllPokemon, getPokemon } from './utils/pokemon';
import Card from './components/Card/Card';
import Navbar from './components/Navbar/Navbar';
function App() {
const initialURL = "https://pokeapi.co/api/v2/pokemon";
const [loading, setLoading] = useState(true);
const [pokemonData, setPokemonData] = useState([]);
const [nextURL, setNextURL] = useState("");
useEffect(()=>{
const fetchPokemonData = async () => {
// 全てのポケモンデータを取得
let res = await getAllPokemon(initialURL);
// 各ポケモンの詳細なデータを取得
// console.log(res.next);
loadPokemon(res.results);
setNextURL(res.next); #追記
setLoading(false);
};
fetchPokemonData();
},[]);
#省略
#以下追記
const handleNextPage = async () => {
setLoading(true);
let data = await getAllPokemon(nextURL);
await loadPokemon(data.results);
setLoading(false);
console.log(data);
};
const handlePrevPage = () => {
};
return (
<>
#省略
<div className='btn'>
<button onClick={handlePrevPage}>前へ</button>
<button onClick={handleNextPage}>次へ</button>
</div>
#省略
</>
);
}
export default App;
次の次のページのポケモンを検索するボタンを作成
App.js
import { useEffect, useState } from 'react';
function App() {
const [nextURL, setNextURL] = useState("");
#省略
const handleNextPage = async () => {
setLoading(true);
let data = await getAllPokemon(nextURL);
await loadPokemon(data.results);
setNextURL(data.next); #追記
setLoading(false);
console.log(data);
};
#省略
前のページに戻る
App.js
import { useEffect, useState } from 'react';
#省略
function App() {
#省略
const [prevURL, setPrevURL] = useState(""); #追記
useEffect(()=>{
const fetchPokemonData = async () => {
// 全てのポケモンデータを取得
let res = await getAllPokemon(initialURL);
// 各ポケモンの詳細なデータを取得
// console.log(res.next);
loadPokemon(res.results);
setNextURL(res.next);
setPrevURL(res.previous); #追記
setLoading(false);
};
fetchPokemonData();
},[]);
#省略
const handleNextPage = async () => {
setLoading(true);
let data = await getAllPokemon(nextURL);
await loadPokemon(data.results);
setNextURL(data.next);
setPrevURL(data.previous); #追記
setLoading(false);
console.log(data);
};
#以下追記
const handlePrevPage = async () => {
if(!prevURL) return;
setLoading(true);
let data = await getAllPokemon(prevURL);
await loadPokemon(data.results);
setNextURL(data.next);
setPrevURL(data.previous);
setLoading(false);
};
#省略
ボタンをcssでスタイリング
App.css
.btn {
padding: 30px 0;
display: flex;
justify-content: center;
align-items: center;
gap: 20px;
}
.btn button {
padding: 13px 32px;
background-color: rgb(99, 74, 51);
border: none;
box-shadow: 6px 9px 15px -5px #777777;
border-radius: 5px;
color: white;
cursor: pointer;
transition: all 0.3s;
}
.btn button:hover {
transform: translateY(5px);
box-shadow: none;
}