I have a local image and I want to put on my webpage with Props. I did src={require('../images/my-image.png')}
but it didn't work.
It only works with importing the image file, But I want it to be dynamic.
The resulting img element is this:
App.js:
export default function App() {
return (
<div className="App">
<Cards img="my-image.png" />
</div>
)
}
Cards.js:
export default function Card(props) {
return (
<div>
<img src={`../images/${props.img}`} />
</div>
)
}
Totally, I can not put image file in src
attribute in JSX, even something like this:
<img src="../images/my-image.png" />
CodePudding user response:
You should move your assets to the public folder instead of keeping them in the src folder. Also, you can use CDN for images if available.
Please refer to this link: React, load images local from json
My Working Code Link: https://codesandbox.io/s/zealous-borg-usgyqv
CodePudding user response:
Can you check the importAll
work for you? Check the below link and confirm if this work for you.
Dynamically import images from a directory using webpack
At the end of importAll, you will have an array of all the images, and based on your requirement, you can pass the specified image as prop to Cards.js
CodePudding user response:
This is very simple if you have a 'png' all you have to do is import the 'png' then pass it as a prop. Your mistake is trying to use a relative path:
This is not correct
<img src={../images/${props.img}
} />
This is the correct way : <img src={props.img}/>
If you want to load an SVG the best way is to convert it into a React component like this.
import React from 'react'
export default function MySVG() {
return (
<svg className="leftArrowSvg" width="6px" height="10px" viewBox="0 0 6 10" version="1.1" xmlns="http://www.w3.org/2000/svg">
<g id="Version-1" stroke="none" strokeWidth="1" fill="none" fillRule="evenodd" strokeLinecap="round" strokeLinejoin="round">
<g id="Replay-Meeting---Key-Word-Tag" transform="translate(-37.000000, -40.000000)" stroke="#ffffff" strokeWidth="2">
<g id="Header" transform="translate(0.000000, 24.000000)">
<g id="Back-Button" transform="translate(38.000000, 8.000000)">
<polyline id="Arrow" transform="translate(2.000000, 13.000000) rotate(-360.000000) translate(-2.000000, -13.000000) " points="4 9 0 13 4 17"> </polyline>
</g>
</g>
</g>
</g>
</svg>
)
}
CodePudding user response:
hello if you want to make the image url dynamic you can write it like this :
<img src={require(`../images/${image}`)} alt="product" />
reference : Load images based on dynamic path in ReactJs