Exercice React : Pokedex
Création d’un Pokedex en utilisant l’API Pokémon
Dans cet exercice, vous allez apprendre à créer un mini Pokedex en utilisant React et l’API Pokémon (PokeAPI) pour afficher des informations sur les Pokémon.
Objectif :
Créer une application React qui permet :
- D’afficher une liste de Pokémon.
- De rechercher un Pokémon par nom.
- D’afficher des détails sur un Pokémon sélectionné (nom, image, type, etc.).
Étape 1 : Configuration de Base
Structurez le Projet
Organisez votre projet comme suit :
src/
|-- components/
| |-- PokemonList.jsx
| |-- PokemonDetails.jsx
| |-- SearchBar.jsx
|-- App.js
|-- App.css
Étape 2 : Afficher une Liste de Pokémon
Création du Composant PokemonList
PokemonList.jsx
import React, { useEffect, useState } from 'react';
function PokemonList({ onPokemonClick }) {
const [pokemons, setPokemons] = useState([]);
const [loading, setLoading] = useState(true);
useEffect(() => {
fetch('https://pokeapi.co/api/v2/pokemon?limit=50')
.then((response) => response.json())
.then((data) => {
setPokemons(data.results);
setLoading(false);
})
.catch((error) => console.error('Erreur :', error));
}, []);
if (loading) {
return <p>Chargement des Pokémon...</p>;
}
return (
<div>
<h2>Liste des Pokémon</h2>
<ul>
{pokemons.map((pokemon, index) => (
<li key={index} onClick={() => onPokemonClick(pokemon.name)}>
{pokemon.name}
</li>
))}
</ul>
</div>
);
}
export default PokemonList;
Explication :
• fetch() : Récupère une liste de 50 Pokémon depuis l’API. • onPokemonClick : Une fonction passée depuis le parent, déclenchée lorsqu’un Pokémon est cliqué.
Étape 3 : Rechercher un Pokémon
Création du Composant SearchBar
SearchBar.jsx
import React from 'react';
function SearchBar({ onSearch }) {
return (
<div>
<input
type="text"
placeholder="Rechercher un Pokémon"
onChange={(e) => onSearch(e.target.value.toLowerCase())}
/>
</div>
);
}
export default SearchBar;
Explication :
• onSearch : Une fonction passée depuis le parent pour filtrer les Pokémon en fonction de la recherche.
Étape 4 : Afficher les Détails d’un Pokémon
Création du Composant PokemonDetails
PokemonDetails.jsx
import React, { useEffect, useState } from 'react';
function PokemonDetails({ pokemonName }) {
const [pokemon, setPokemon] = useState(null);
useEffect(() => {
if (!pokemonName) return;
fetch(`https://pokeapi.co/api/v2/pokemon/${pokemonName}`)
.then((response) => response.json())
.then((data) => setPokemon(data))
.catch((error) => console.error('Erreur :', error));
}, [pokemonName]);
if (!pokemonName) {
return <p>Sélectionnez un Pokémon pour voir ses détails.</p>;
}
if (!pokemon) {
return <p>Chargement des détails...</p>;
}
return (
<div>
<h2>{pokemon.name}</h2>
<img
src={pokemon.sprites.front_default}
alt={pokemon.name}
style={{ width: '150px' }}
/>
<p><strong>Type :</strong> {pokemon.types.map((type) => type.type.name).join(', ')}</p>
<p><strong>Taille :</strong> {pokemon.height}</p>
<p><strong>Poids :</strong> {pokemon.weight}</p>
</div>
);
}
export default PokemonDetails;
Explication :
- Détails du Pokémon : Récupérés via une requête API lorsque l’utilisateur clique sur un Pokémon.
- Affichage dynamique : Les types, la taille, et le poids du Pokémon sont affichés.
Étape 5 : Intégrer le Tout dans App.js
App.jsx
import React, { useState } from 'react';
import PokemonList from './components/PokemonList';
import PokemonDetails from './components/PokemonDetails';
import SearchBar from './components/SearchBar';
import './App.css';
function App() {
const [searchTerm, setSearchTerm] = useState('');
const [selectedPokemon, setSelectedPokemon] = useState(null);
const handleSearch = (term) => {
setSearchTerm(term);
};
const handlePokemonClick = (name) => {
setSelectedPokemon(name);
};
return (
<div className="app">
<h1>Pokedex</h1>
<SearchBar onSearch={handleSearch} />
<div className="content">
<div className="list">
<PokemonList
onPokemonClick={handlePokemonClick}
searchTerm={searchTerm}
/>
</div>
<div className="details">
<PokemonDetails pokemonName={selectedPokemon} />
</div>
</div>
</div>
);
}
export default App;
Étape 6 : Ajout de Styles avec CSS
app.css
body {
font-family: Arial, sans-serif;
background-color: #f8f9fa;
margin: 0;
padding: 0;
}
.app {
text-align: center;
padding: 20px;
}
.content {
display: flex;
justify-content: space-around;
margin-top: 20px;
}
.list {
flex: 1;
margin-right: 20px;
}
.details {
flex: 1;
text-align: left;
padding: 10px;
background-color: #fff;
border: 1px solid #ddd;
border-radius: 5px;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}
ul {
list-style: none;
padding: 0;
}
li {
padding: 10px;
margin: 5px 0;
cursor: pointer;
background-color: #f1f1f1;
border-radius: 5px;
transition: background-color 0.3s;
}
li:hover {
background-color: #e0e0e0;
}
Étape 7 : Résultat Final
- Liste de Pokémon : Cliquez sur un nom pour voir les détails.
- Recherche : Tapez un nom pour filtrer les Pokémon.
- Détails : Affichez l’image, les types, la taille, et le poids du Pokémon sélectionné.
Concepts Appris
- Utilisation de fetch() pour appeler une API.
- Gestion du state avec useState.
- Gestion des effets secondaires avec useEffect.
- Création de composants réutilisables.
- Application de styles CSS pour améliorer l’apparence.
Vous avez maintenant un mini Pokedex fonctionnel ! 🎉