i have a issue with setting the src of an Card.Img element, this element is being generated via a .map() which maps the props of an object from an array, let me show you:
const items = [
{name:"Banana",price:4,img : './imgShop/pexels-any-lane-5945848.jpg',id:1},
{name:"Apple",price:2,img : './imgShop/pexels-bruno-scramgnon-575610.jpg',id:2},
{name:"Orange",price:4,img : './imgShop/pexels-dominika-roseclay-2090902.jpg',id:3},
{name:"Lemon",price:3,img : './imgShop/pexels-lukas-1414110.jpg',id:4},
{name:"Pumpkin",price:10,img : './imgShop/pexels-miguel-á-padriñán-673073.jpg',id:5},
{name:"Kiwi",price:5,img : './imgShop/pexels-pixabay-51312.jpg',id:6},
{name:"Green apple",price:3,img : './imgShop/pexels-pixabay-533343.jpg',id:7},
{name:"Cherry",price:1,img : './imgShop/pexels-lisa-109274.jpg',id:8},
{name:"Guacamole",price:7,img : './imgShop/pexels-dominika-roseclay-2095924.jpg',id:9},
{name:"Melon",price:12,img : './imgShop/pexels-brian-van-den-heuvel-1313267.jpg',id:10},
{name:"Pomegranate",price:9,img : './imgShop/pexels-karolina-grabowska-4226732.jpg',id:11},
{name:"Pear",price:2,img : './imgShop/pexels-mali-maeder-568471.jpg',id:12},]
And
const Shop = () => {
let firstArray = items.slice(0,4)
let secondArray = items.slice(4,8)
let thirdArray = items.slice(8)
return(
<div id="shop-container" className="container d-flex">
<div className="col">
{firstArray.map(item => {
return(
<Card style={{ width: '18rem' }} key={item.id}>
<Card.Img variant="top" src={require(item.img)} />
<Card.Body>
<Card.Title>{item.name}</Card.Title>
<Card.Text>
Some quick example text to build on the card title and make up the bulk of
the card's content.
</Card.Text>
</Card.Body>
</Card>
)
})}
</div>
<div className="col">
</div>
<div className="col">
</div>
</div>
)
}
I already try putting only the path of one image and works, but when i put item.img throws me that error, and i have to use the require function because if not webpack doesn't process the img
CodePudding user response:
You can import them one by one like this
import image1 from "./imgShop/pexels-any-lane-5945848.jpg";
import image2 from "./imgShop/pexels-bruno-scramgnon-575610.jpg";
..........
Then use image1
, image2
in your items
array like img:{image1}
OR
You can create a new js file to export those images for you like this.
import image1 from './imgShop/pexels-any-lane-5945848.jpg';
import image2 from './imgShop/pexels-bruno-scramgnon-575610.jpg';
export default [
image1,
image2,
];
then import then on your main js file
import imagesArray from './images';