Home > front end >  React Image - Local Image not showing
React Image - Local Image not showing

Time:11-14

import styled from 'styled-components';
import bannerImage from '../img/bannerImage.jpg';

console.log(bannerImage);

const StyledBanner = styled.div`
    margin-top: 55px;
    width: 100%;
    height: 20px;
    background-color: red;
`;

function Banner() {
    return (
        <StyledBanner>
            {/* <img src={`http://github.com/someprofile.png`} /> */}
            <img src={require("../img/bannerImage.jpg")} />
            <img src={bannerImage} />
        </StyledBanner>
    );
};

export default Banner;

I have this React Component that I am trying to return a local image, but this image never loads, it show the image is there but it is always broke. I tried using require method and also the import but nothing works.

When it is an external image it works fine, only when it is local it doesnt work.

Could you please advise me how to correct this issue?

The final element that comes out of this is a DIV and those 2 images there appear as broken images, but if I change the src to a online picture it works fine.

<div >
<img src="[object Module]">
<img src="[object Object]">
</div>

CodePudding user response:

I think the fix is going to be to use require("../img/bannerImage.jpg").default, because require returns an object with a default property that you have to access.

Example from an old project of mine:

If I set my state like this:

setProfileImg(require("../images/"   res.data.profileImg));

it has the value of this object:

{
  "default": "/static/media/1640086164286.e03de477.png"
}

And so by using .default I access the actual image path I want.

  • Related