I am learning React.js and aiming to make a product page, and I have some issues with importing images from my local directory. These are from my actual project, but it's an online editor, but it should be fine because it's the same issue. These are my files:
My App.js:
import "./styles.css";
import Images from "./Images";
export default function App() {
return (
<div className="container">
{Images.map((content) => (
<div className="product-image">
<img src={content.image} />
</div>
))}
</div>
);
}
My Images.js:
const Images = [
{
id: 1,
image: "./img/img1.jpg"
},
{
id: 2,
image: "./img/img2.jpg"
},
{
id: 3,
image: "./img/img3.jpg"
}
];
export default Images;
For Image.js, It is weird because if I make the image source to a url format, it works fine. The local directory name shouldn't be a problem because that's where I imported other sources in my project. Any helps would be appreciated.
For this to work, you have two choices, either you put your img folder inside public folder and change Images.js to this:
const Images = [
{
id: 1,
image: "/img/img1.jpg"
},
{
id: 2,
image: "/img/img2.jpg"
},
{
id: 3,
image: "/img/img3.jpg"
}
];
export default Images;
Or you keep img folder inside src and change Images.js to this:
import img1 from "./img/img1.jpg";
import img2 from "./img/img2.jpg";
import img3 from "./img/img3.jpg";
const Images = [
{
id: 1,
image: img1
},
{
id: 2,
image: img2
},
{
id: 3,
image: img3
}
];
export default Images;
See this Stack Overflow QA to know why it's like this.