This is the parent component. I created data.js
and in that data.js
I have exported products object where I have written id and img source path. I have posted the image and you can see the file structure there also. I tried both of the image source path from data.js and product.js but none of them work
const ProductList = () => {
return (
<div className='productlist'>
<div className="pl-texts">
<h2 className="productlist_title">
Create & inspire. It's David
</h2>
<p className="productlist_desc">
David is a creative portfolio that your work has been waiting for. Beautiful homes, stunning portfolio styles & a whole lot more awaits inside.
</p>
</div>
<div className="product-list">
{products.map((item) => (
<Product key={item.id} img={item.img}/>
))}
</div>
</div>
)
}
//This is the child component
import './product.css'
const Product = ({img}) => {
console.log(img)
return (
<div className='product'>
<div className="p-browser">
<div className="p-circle"></div>
<div className="p-circle"></div>
<div className="p-circle"></div>
</div>
<img className='p-img' src={img} alt="" />
//If I give direct img path then it works. I have sent img path in the props.
</div>
)
}
export default Product
CodePudding user response:
There are two ways to put images into your app. You have to pick one.
- We can put images in public folder, and pass image's path to
<img />
(More info: https://create-react-app.dev/docs/using-the-public-folder)
Let's say we have /img in public folder.
/public
/img
/ecommerce.PNG
Then we can show the image by give http path to image (yourdomain.com/img/ecommerce.PNG
)
<img src="/img/ecommerce.PNG" /> // Notice there's no ../../ in the path.
- We can import a file right in a JavaScript module (More info: https://create-react-app.dev/docs/adding-images-fonts-and-files)
/src
/img
/ecommerce.PNG
Then we can show the image by
import ecommerceImage from '../img/ecommerce.PNG';
<img src={ecommerceImage} />
In your scenario, the quickest fix would be edit the products data into
const products = [
{ id: 1, img: require('../../img/ecommerce.PNG') },
{ id: 2, img: require('../../img/adminportal.PNG') },
{ id: 3, img: require('../../img/imagegallery.PNG') },
{ id: 4, img: require('../../img/netflix.PNG') },
];