Connor
Connor

Reputation: 279

Img tag src issues

I am having trouble using the img tag in a react app.

My file structure looks like this:

Project
 |    
 +-- assets
 |  |  
 |  \-- pic.png
 |    
 +-- views
 |  |  
 |  |-- Home
 |     |
 |     |-- index.js
 |     \-- index.css

I have an <img> tag in views/Home/index.js

the specific line I use is:

<img src="../../assets/pic.png" alt="pic"/>

But it says it can not find the file. However, if I use a <div>, instead of an <img> tag, and use css to get the file from views/Home/index.css:

.pic-container {
  background-image: url("../../assets/pic.png");
}

<div className="pic-container"/>

It works fine.

What is going on here?

Upvotes: 0

Views: 135

Answers (1)

seanulus
seanulus

Reputation: 885

In React, you usually need to either require the image or import it into your component.

<img src={ require("../../assets/pic.png") } alt="pic"/>

Or..

import pic from "../../assets/pic.png"
...
<img src={pic} alt="pic"/>

Upvotes: 3

Related Questions