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]}/>;
Related
I am creating one word add-in which will display image details in table and image in next page after clicking on particular image in DOM. I want to add hyperlink to every images of table. For adding hyperlink, I have to create bookmark on each and every images going to be insert. Here I have tried to get all the images of document and adding bookmark on that images.
await Word.run(async (context) => {
const pictures = context.document.body.inlinePictures;
pictures.load()
await context.sync();
pictures?.items?.map((item)=>{
console.log("items",item);
let bookmarkName = "Bookmark" + new Date().getTime()
const bookmarkObj = { "ImageId": item.altTextTitle, "bookmark": bookmarkName }
console.log("data called");
bookmarkArr.push(bookmarkObj)
console.log("bookmarkArr", bookmarkArr);
localStorage.setItem('bookmark', JSON.stringify(bookmarkArr))
item.insertBookmark(bookmarkName)
})
})
here, it is giving type error for insertBookmark() and saying that insertBookmark() is not a function. I have to inform you that If I am adding bookmark for single image, it is working fine but when I tried for multiple images it is not working.
Your item variable is type InlinePicture. This type does not have an insertBookmark method.
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
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
I have a socket connection that updates a binary data.
By click I would like to update an image src , the images are created blank with empty src and with id , but I did not found how do I doing something like :
$('imageId').src = 'new src' like in Jquery
I have array of images so I cant define per each image this.ref or something
my socket code: // here I want to update the specific image
divSocket.on('data', (data) => {
var bytes = new Uint8Array(data);
this.setState({
imageSrc : someBufferFunction(bytes)
})
});
my render code
{ this.props.list.map((item,i) =>(
<div className="img">
<img id={`cam${i}`} src={`data:image/jpeg;base64,${this.state.imageSrc}`} />
</div>
))}
the problem is that this.state.ImageSrc will update all images and will show socket data (video) in all the images
I can create an image with specific id in loop but how do I update specific image via props/state
You're using an array to display images ... from props ... this.props.list
This list should contain data for each image ... but item argument isn't used in .map rendering.
I need to make a placeholder
Assuming that props.list doesn't contain any data ... used as loop counter ... renders placeholders only ... you need:
an array of src in local state (this.state.sources = [];)
you should render images using key prop:
{ this.props.list.map((item,i) => (
<div className="img" key={`cam${i}`} >
<img id={`cam${i}`} src={this.state.sources[i]} />
</div>
))}
you can use placeholder image for empty 'cells'
<img id={`cam${i}`} src={this.state.sources[i] ? this.state.sources[i] : "url_somePlaceholder.jpg"} />
New image from socket needs to update an array element using index - not common one for all images in this.state.sources - see React: how to update state.item[1] in state using setState? for inspirations.
If assumed earlier props.list contains image sources at start - copy values into state (in componentDidMount, componentDidUpdate or static getDerivedStateFromProps )
I have been following a tutorial to query Stripe API and display data. One thing that is not mentioned is how to query the images and display it. I can see from the structure that the images property is there but I need some help to display it. I assume it should be the same logic how it is displaying the product name but I just need to understand to follow the same logic for the images.
Here is my query, I have added the image option in my query:
and can see the result in GrapiQL:
Here is example of how I am mapping over my products to display correctly. From what I understand I need to do the same for the image. I have followed the same logic by just replacing product with image but just can't seem to get it working. Here is the snippet:
const Products = () => {
return (<StaticQuery query={PRODUCTS_QUERY}
render={
({ allStripeSku, allStripeProduct }) => {
return allStripeProduct.edges.map(product => {
const skus = allStripeSku.edges.filter(
sku => sku.node.product.id === product.node.id
)
return (
<Product
key={product.node.id}
skus={skus}
product={product.node} />
)
})
return
}
}
/>)
}
Can anyone please point my in the right direction so I can get this working?
You need to add 2 lines of code:
in GraphQL query to return images alongside id and name as you've already done
in ProductCard component to return an <img> element using the query field added above
For me this meant adding the + lines below:
in src/components/Products/Products.js
in src/components/Products/ProductCard.js
I assume it's the Gatsby E-commerce Tutorial you were following; if so please be aware that, since your OP, they've updated the docs so it no longer uses the deprecated Orders API.