'Unable to display pokemon image from pokeapi.co
I am having an issue where I can't seem to be able to display the pokemon images on my react front end, this is the api: https://pokeapi.co/
import React, { Component } from 'react';
class Card extends Component {
state = {
name: "",
imageUrl: "",
pokemonIndex: "",
}
componentDidMount() {
const {name, url} = this.props;
const pokemonIndex = url.split('/')[url.split('/').length - 2];
const imageUrl = `http://pokeapi.co/media/sprites/pokemon/${pokemonIndex}.png`
this.setState({name, imageUrl, pokemonIndex})
}
render() {
return (
<div className="card" >
<img src= {this.state.imageUrl}/>
<h3> {this.state.name} </h3>
</div>
);
}
}
export default Card;
Solution 1:[1]
Looking at the documentation and JSON file from API, I think I found your problem. You are using the wrong img link. The correct format is: https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/${pokemonIndex}.png
For exemple:
<img src="https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/132.png" />
Solution 2:[2]
@erick-silva answer is not complete and prone to error.
The correct way to fetch an image for a specific pokemon is:
- Fetch from PokeAPI the info for that pokemon, say
bulbasaur. ->GET https://pokeapi.co/api/v2/pokemon/bulbasaur - Parse the returned JSON for the property
.sprites, select the version we'd like to use and the variety for the sprite, say Pokemon Crystal front:.sprites.versions["generation-ii"].crystal.front_default - Use the provided link and load the image: https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/versions/generation-ii/crystal/1.png
Using this method will ensure that you will always fetch the correct image in case the ids change or the name of the image isn't the id of the pokemon.
Solution 3:[3]
For pokeapi the correct URI format is as follows.
https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/imageName.png
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Erick Silva |
| Solution 2 | Naramsim |
| Solution 3 | Dharman |

