Require Path For Src Image As Variable
I'm working on a react project created with the create-react-app. I've got an array of data objects. One of the properties in the object is an image path. If I put the path directl
Solution 1:
The error is because when the react app is hosted then the image path changes to a dynamic value which is relative to the path of your host. This is due to bundling by webpack. So react uses require.context which comes from webpack.
export json and get all your required paths. Then do as follows
var cache = [];
function importAll (r) {
r.keys().forEach((key,index) => cache[index] = r(key));
}
//path from json
importAll(require.context(path, false, /\.(png|jpe?g|svg)$/));
export default cache;
cache will be an array of all the images you need
in your img tag do as follows
<img src={cache[0]}/>
if you already know the path you could just import it as
import img from imgPath
...
<img src = {img}/ >
Hope this helps
Post a Comment for "Require Path For Src Image As Variable"