EdG
EdG

Reputation: 2351

Error while trying to add image to react project

I am working on a react project. I am trying to add an image to one of my components. I made a directory named "images" in my project structure tree and I have put my image in this directory (image of project structure is attached below). I want to pass this image as src to my img tag. For this I right clicked on image and selected "copy image path" and then pasted that path to src of img tag. But when I try to run it, I get an error saying "Failed to load resource: the server responded with a status of 404 (Not Found)". Here is my code of component and screenshot of project structure.

P.S. I am on Ubuntu Environment

export default class CustomizedAppComponent extends Component {
    render(){
        return(
            <div>
                <img src="/home/user/Documents/Tessact-Master/dev/js/images/logo.png"/>
            </div>
        );
    }
}

Project Structure

Upvotes: 1

Views: 6401

Answers (2)

Shubham Khatri
Shubham Khatri

Reputation: 281726

First of all the src of the image must be relative to the location of the component it is used in. Assuming the CustomizedAppComponent to be in the components or containers folder your image path must look like

 "../images/logo.png"/

if the component is again inside another folder inside folder components, then give path as

"../../images/logo.png"/             // add '../' so on 

Also in react you may need to mention the src within a require if you are using webpack to transpile your jsx and if not and then omit require in the below code.

export default class CustomizedAppComponent extends Component {
    render(){
        return(
            <div>
                <img src={require("../images/logo.png")}/>
            </div>
        );
    }
}

Upvotes: 0

Kishore Chandra
Kishore Chandra

Reputation: 606

No Need to use ../ or require in your url.. SIMPLE TRICK: It is very important from where you are serving you app. If you are serving your app from Tessact-Master then you code should be like this below

use just /dev not ./dev

export default class CustomizedAppComponent extends Component {
    render(){
        return(
            <div>
                <img src={"/dev/js/images/logo.png"}/>
            </div>
        );
    }
}

Upvotes: 2

Related Questions