Unable to display pokemon image from pokeapi.co - reactjs

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;
I have also attached a screenshot of the front end.

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" />

#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.

For pokeapi the correct URI format is as follows.
https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/imageName.png

Currently pokemon images are not loaded as there are deleted from it's github repo.
You can find the real location of the images inside sprites folder in PokeAPI GitHub.
To get the image, there is a workaround,
https://unpkg.com/pokeapi-sprites#2.0.2/sprites/pokemon/other/dream-world/1.svg
here 1.svg should be replaced by the pokemon's id
You can find more info here

Related

In react, how to pass a dynamic link in sms href?

React-share is a nifty tool but.... doesn't have sharable sms support that I can find. Need some pointers. //will send virtual coffee as a thanks!B)
The challenge: share a dynamically created product url as a text message, with the dynamic description and url.
I have tried several link additions, but not able to accomplish the result I am looking for. Here is most recent try:
<FontAwesome name="share" />
Another one I tried (which is what I use for non-dynamic links) at least drops text into the body is:
<FontAwesome name="share" />
After working this through, here is what we ended up going with, no phone number at all, just the description and url in the body of the message.
First:
const objectEncode = object => {
const str = [];
Object.keys(object).forEach(key => {
str.push(`${encodeURIComponent(key)}=${encodeURIComponent(object[key])}`);
});
return str.join('&');
};
export default objectEncode;
Then:
import objectEncode from '../../../utils/objectEncode';
Then within the component:
render(){
const smsBody = objectEncode({ body: `${description} ${url}` });
return (
<a href={`sms://?&${smsBody}`} className="social-link">
<FontAwesome name="commenting" />
</a>
);
}

Unable to resolve an image in an array in React JS

I'm attempting to import images into an array in React JS. My intention is to be able to map through the array and have the images appear one as a time. However, my images are not being properly resolved. I'm fairly certain it is a syntax error of my doing, but I'm just not able to solve this. I'm currently a student who is just learning react, so any and all help is much appreciated!
import universe from "./images/universespider.jpeg"
let content = [
{
title: "Universe",
image: universe,
author: "Alex",
date: "09/09/8099",
blog: "Spider-Man is in different universes.",
},
]
import "./blogs.css"
import content from "../../content"
export default function blogs() {
return (
content.map((blog, i) => (
<div key={i}>
<div className="blogBox">
{blog.title}
{blog.image}
{blog.author}
{blog.date}
{blog.blog}
</div>
</div>
)
))
}
Error Message
You can't use imported images directly, in your case you should use element and pass your image as a source.
Instead of
{blog.image}
try this
import universe from "./images/universespider.jpeg"
...
<img src={universe} alt="universe"/>
More information about this assuming that your app was created with CRA.

React: Using State Variable In Image Src?

So I've exported all of the images in my image folder by using an index.js inside the same folder and writing exports such as export const Image = require("./image.png");. I then imported said images into my React app with import { Image, Image2, Image3 } from from "./imageFolder";
When I use the imported images as src values in my image tags, they work just fine so I know I've properly imported my image. The big issue that I have though is I've been trying to utilize the value of a state variable in the file to dynamically render a different image based on the state. The state variable's values are varied due to its values deriving from a database request that's stored in a state array.
{
Object.keys(this.state.videos).map((video, index) => {
return (
<div key={index}>
<p>Event: {this.state.videos[video].eventName}</p>
<p>P1 Character: {this.state.videos[video].p1Character}</p>
<p>P2 Character: {this.state.videos[video].p2Character}</p>
</div>
);
})
}
Say that in this instance, the value of {this.state.videos[video].p1Character} is equal to "Image" - which corresponds with the name of the image I imported above. So why can't I do <img src={this.state.videos[video].p1Character} />? Is it possible to do what I'm trying to do?
You cannot do it becaue the p1Character is a string and not a live variable.
You could however import the images as
import * as Images from from "./imageFolder";
and then use the p1Character to reference the image in the Images.
<img src={Images[this.state.videos[video].p1Character]} />
Unless I don't understand what you mean, I don't see how it would be possible to have this this.state.videos[video].p1Character equal to Image/Image2/Image3 if you have just save a reference to them as a string because you are literally just going to be writing src="Image/2/3".
The best thing to do would to be store a unique key string for the images on a record and then just have a simple object map in your component like
const myImageMap = {
image1: Image,
image2: Image2,
image3: Image3
}
/////
///// somewhere in your render
/////
<img src={myImageMap[this.state.videos[video].p1Character]} />
They key is that we are mapping to the strings to actual imported images

Unable to display images after uploading them in react component

I want to upload multiples images then display them in browser. I wrote this code mentioned by this link.
I got the name of images displayed in place of images:
Image1.png
Image2.png
How can I fix that and if someone knows another npm module which upload and display images as a gallery I will be grateful if mentioned it to me.
Adding the property withPreview to the <ImageUploader /> gives you a preview of all "uploaded" images.
const UploadImage = props => {
const { onDrop } = props;
return (
<ImageUploader
withIcon
buttonText="Upload Image"
onChange={onDrop}
imgExtension={[".jpg", ".gif", ".png", ".gif"]}
maxFileSize={5242880}
withPreview
/>
);
};
You can see this change implemented here.
This library looks like it can achieve what you want right out the box. See the documentation for the library for more details.

React add images to existing map

I have a react app where I fetch the item data from an API.
I'm mapping each item's data to a card in the react app.
this.props.item.map(item => {
return <Card data={item.name} key={item.id}/>;
This works, however I want to add a corresponding image to each item in the array and I'm not sure what approach to take to add images to an existing map.
The images are stored in the public folder and not available via the API. I want the correct image to correspond to the correct data.
Eg. data="flowers" key="123" src="../images/flowers.jpg"
Thanks!
Initially take the images from the public folder and add it to somewhere inside src say, src/assets/images.
Then you will have to create an object corresponding to each data value. Then map the value to the image name.
var flower = require("../assets/images/flowers.jpg");
var cat = require("../assets/images/cat.jpg");
var dog = require("../assets/images/dog.jpg");
var dictionary={"flowers":flower, "cat":cat,"dog":dog}
now when you get response from API,
you can use inside the card component as,
<img src={dictonary[props.name]}/>
You could add a new prop named src, and use it with the name of the item:
this.props.item.map(item => {
return <Card data={item.name} key={item.id} src={`${item.name}.jpg`}/>;
You can create an image to item.id map and there you can find image from your local.
example:
const imageIdMapper = {
1: require("./<path to image belongs to id one>),
2: require("./<path to image belongs to id two>),
...
}
then in your map
this.props.item.map(item => {
return <Card data={item.name} key={item.id} image={imageIdMapper[item.id]}/>;

Resources