Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getting broken image in React App

Tags:

image

reactjs

I am trying to access an image in a React App. When I run the code I get a broken image icon on web page. I am not sure if I am accessing the right path for the image. The code I have is the following:

import React, { Component } from 'react';

class HeaderName extends Component {
    render() {
        return (
            <div>
                <h1>The AquaStars New Website.</h1>
                <img src="./images/picture_swimmers.png" />
            </div>
            )
        }
}

export default HeaderName; 

The structure of the code is the followingenter image description here

like image 862
AltBrian Avatar asked Oct 24 '25 05:10

AltBrian


2 Answers

Seems like you are using the wrong path. If I am seeing this correct the code you posted above is from header.js which is in the src folder. Since your images folder is in public you would need to step up one folder then over to public first. The path you would want to use is,

    ../public/images/picture_swimmers.png

Just note if you plan on creating a production build this path would be different. One suggestion I have used before is if the images must be in the public folder then you can reference them like,

    src={process.env.PUBLIC_URL + '/images/picture_swimmers.png'}
like image 65
Matthew Zielke Avatar answered Oct 26 '25 18:10

Matthew Zielke


I was having the same issue today, my image appeared broken.

When I imported the image first in the component it worked fine, in your case it will look something like the code below.

import React, { Component } from 'react';
import image from './images/picture_swimmers.png'    
    
class HeaderName extends Component {
    render() {
        return (
            <div>
                <h1>The AquaStars New Website.</h1>
                <img src={image} />
            </div>
            )
        }
    }
    
   export default HeaderName;
like image 36
Ashutosh Mishra Avatar answered Oct 26 '25 19:10

Ashutosh Mishra