Reputation: 1145
I have been following a YouTube tutorial for making a website using react.js.
index.js:
import { Img, ImgWrap } from './InfoElements';
const InfoSection = ({ img, alt)} => {
return(
<>
<ImgWrap>
<Img src={img} alt={alt}/>
</ImgWrap>
</>
)
}
export default InfoSection
I have been exporting image src from another folder named Data.js
Data.js:
export const homeObjOne = {
img: require("../../images/svg-1.svg"),
alt: 'error404'
}
I used styled-components for style
InfoElements.js:
export const ImgWrap = styled.div`
max-width: 555px;
height: 100%;
`;
export const Img = styled.img`
width: 100%;
margin: 0 0 10px 0;
padding-right: 0;
`;
Here image is placed on
src->images->svg-1.svg
I tried using other images like jpe, jpg and png rather than svg but still its not working. The image is not showing on background.
Here is the picture the way image return:
Here is the path of image folder:
I have been tried all other image format and result is same..Is their anything I done wrong
Upvotes: 1
Views: 7503
Reputation: 23
Follow this article https://www.freecodecamp.org/news/unable-to-find-images-based-on-url-in-react/.
Move images folder under /public
not /src
.
In data.js
img: "./images/svg-1.svg"
Or use you can use import
, like this import image1 from "./images/1.jpg
Upvotes: 2
Reputation: 2623
Your structure is falling victim to a default export naming issue. When you require your image in Data.js, you're setting it as a module. If you want to access the URL of the image, you need to use:
export const homeObjOne = {
img: require("../../images/svg-1.svg").default, //note the default part at the end
alt: 'error404'
}
Although this could be made cleaner using imports:
import homeObjOne from "../../images/svg-1.svg";
export const homeObjOne = {
img: homeObjOne, //no need for default here, thanks to import
alt: 'error404'
}
Note: If you inspect your image whilst it is broken, you'll see the src will be [object Object]
.
Upvotes: 8