Estoy construyendo una caja de luz en React que recorre una serie de objetos, pero parece que no puedo mostrar la imagen y el texto. En última instancia, quiero que cada imagen tenga texto sobre ella que solo identifique cada plaga.
El error es que obtengo objetos vacíos en la página. Estoy seguro de que estoy haciendo algo increíblemente tonto;)
[object Object]¿Alguien podría tener alguna idea sobre cómo hacer que esto funcione o si hay algo que me estoy perdiendo? Gracias por adelantado.
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); } };Aquí está la declaración de devolución y el resto.
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;Olvidó desestructurar los valores del objeto al mapear. Tienes que cambiar esto:
const imageCards = images_arr.map((image, text) => ( <img key={image} alt={image} className="image-card" onClick={() => showImage(image)} src={image} /> ));a esto:
const imageCards = images_arr.map(({image, text}) => ( <img key={image} alt={image} className="image-card" onClick={() => showImage(image)} src={image} /> ));