I have this data
[
{
"filePath": "imageFile",
"locationName": "name1"
},
{
"filePath": "imageFile",
"locationName": "name2"
}
]
and I am returning the value of filePath to display images using React js in a card like this:
const images = (displayimage) => {
return displayImages.map((displayimage, key) => (
<div key={key}>
<div className="card bg-light mb-3">
<div className="card-header">
<center>{displayimage.locationName}</center>
</div>
<div className="card-body">
<div className="imgDiv">
<img src={displayimage.filePath} />
</div>
</div>
</div>
</div>
));
}
return <div>{images()}</div>;
};
but only 1 card is returning then the image is returning randomly based on which object is displayed 1st in the console.log(displayImages).
how can I display all each cards per images? Thanks
CodePudding user response:
What you need to store in the images
constant is just the result of calling map()
on your displayImages
array. So assuming you have:
const displayImages = [
{
filePath: "imageFile",
locationName: "name1"
},
{
filePath: "imageFile",
locationName: "name2"
}
];
this is how your component should look like:
const images = displayImages.map((displayimage, key) => (
<div key={key}>
<div className="card bg-light mb-3">
<div className="card-header">
<center>{displayimage.locationName}</center>
</div>
<div className="card-body">
<div className="imgDiv">
<img src={displayimage.filePath} />
</div>
</div>
</div>
</div>
));
return <div>{images}</div>;
Working stackblitz
CodePudding user response:
It looks like your function takes in an argument displayimage
but then you map over a variable called displayimages
(note the s), .
Additionally when you call the function in the return statement there are no arguments provided.
I'm not sure if you've addressed the above issues in your actual code, but it would definitely create problems.
If you have addressed those problems what I would recommend is creating a component called something like ImageCard
that takes in the image location name and file path as props, e.g.
const ImageCard= ({locationName,imagePath}) => {
return (
<div>
<div className="card bg-light mb-3">
<div className="card-header">
<center>{locationName}</center>
</div>
<div className="card-body">
<div className="imgDiv">
<img src={filePath} />
</div>
</div>
</div>
</div>)
};
export default ImageCard;
Then, where you are currently doing your map, iterate over your image data in the return as follows (assuming your data is called displayImages)
return (
displayImages.map(displayImage=>{
return (
<ImageCard
locationName={displayImage.locationName}
imagePath={displayImage.filePath}
/>
);
}
)