I’m building a lightbox in React that loops over an array of objects but I can’t seem to get both the image and text to display. Ultimately I want each image to have text over it just identifying each pest.
The error is that I am getting empty objects on the page. I am sure i am doing something incredibly dumb 😉
[object Object]
Might anyone have any insight on how to get this working or if there’s something I am missing? Thanks in advance.
import { useState } from 'react';
import Ant from '../../img/ant.jpeg';
import Bee from '../../img/bee.jpeg';
import Bedbug from '../../img/bedbug.jpeg';
import Wasp from '../../img/wasp.jpeg';
import Mouse from '../../img/mouse.jpeg'
// const images = [Bee, Ant, Bedbug, Wasp, Mouse];
const images_arr = [
{ image: Ant, text: "Ant" },
{ image: Bee, text: "Bee" },
{ image: Bedbug, text: "Bedbug" },
{ image: Mouse, text: "Mice" },
{ image: Wasp, text: "Wasp" },
]
console.log(images_arr)
function PestsGallery() {
const [imageToShow, setImageToShow] = useState("");
const [lightboxDisplay, setLightBoxDisplay] = useState(false);
//looping through our images array to create img elements
const imageCards = images_arr.map((image, text) => (
<img key={image} alt={image} className="image-card" onClick={() => showImage(image)} src={image} />
));
const showImage = (image, text) => {
setImageToShow(image);
setLightBoxDisplay(true)
}
const hideLightBox = () => {
setLightBoxDisplay(false)
}
const showNext = (e) => {
e.stopPropagation();
let currentIndex = images_arr.indexOf(imageToShow);
if (currentIndex >= images_arr.length - 1) {
setLightBoxDisplay(false)
} else {
let nextImage = images_arr[currentIndex + 1];
setImageToShow(nextImage)
}
}
const showPrev = (e) => {
e.stopPropagation();
let currentIndex = images_arr.indexOf(imageToShow);
if (currentIndex <= 0) {
setLightBoxDisplay(false);
} else {
let nextImage = images_arr[currentIndex - 1];
setImageToShow(nextImage);
}
};
Here’s the return statement and the rest
return (
<>
<h2> Bugs we treat</h2>
<div>{imageCards}</div>
{
lightboxDisplay ?
<div id="lightbox" onClick={hideLightBox}>
<button onClick={showPrev}>⭠</button>
<img alt="gallery" id="lightbox-img" src={imageToShow}></img>
<button onClick={showNext}>⭢</button>
</div>
: ""
}
</>
);
}
export default PestsGallery;
>Solution :
You forgot to destructure the values of the object when mapping. You need to change this:
const imageCards = images_arr.map((image, text) => (
<img key={image} alt={image} className="image-card" onClick={() => showImage(image)} src={image} />
));
to this:
const imageCards = images_arr.map(({image, text}) => (
<img key={image} alt={image} className="image-card" onClick={() => showImage(image)} src={image} />
));