最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Images not loading when relative path is used in React - Stack Overflow

programmeradmin7浏览0评论

I was importing the images previously like this in React:

import person from '../images/image1.png'

And then using them like this:

<img src={person} alt="" />

Now I want to specify the path in the src itself due to some reason, like this:

<img src="../images/image1.png" alt="" />

But it's not working even though it should.

I was importing the images previously like this in React:

import person from '../images/image1.png'

And then using them like this:

<img src={person} alt="" />

Now I want to specify the path in the src itself due to some reason, like this:

<img src="../images/image1.png" alt="" />

But it's not working even though it should.

Share Improve this question edited Jun 13, 2022 at 18:00 Youssouf Oumar 46.6k16 gold badges103 silver badges105 bronze badges asked Jun 13, 2022 at 17:33 Arnab DasArnab Das 331 silver badge10 bronze badges 0
Add a ment  | 

1 Answer 1

Reset to default 7

There are two ways to add images in your JSX with Create React App. The first one is to use import as you did, to import an image that is somewhere in the src folder, like so:

import person from '../images/image1.png'
<img src={person} alt="" />

The second one is to give an image's path to <img>'s src attribute, but it's always relative to the public folder, in a way that the path should start with /, and / means public folder.

See Adding Images, Fonts, and Files and Using the Public Folder on Create React App's documentation.

For your second attempt to work, you could put the images folder inside the public folder, and get your images like so:

<img src="/images/image1.png" alt="" />

If your React app will be in a sub folder when deployed, for the second way to work, you should add in your package.json this "homepage":"www.example./folder", and use process.env.PUBLIC_URL as below.

 <img src={process.env.PUBLIC_URL + "/images/image1.png"} alt="" />
发布评论

评论列表(0)

  1. 暂无评论