3

I have some json with data and one of param is path to my local folder with images:

// data.json
[
  {
    "id": 1,
     "image": "assets/somepic.png"
  },
  {
    "id": 2,
     "image": "assets/anotherpic.png"
  }
  // similar data goes there
]

Then I import those data into my component

import data from "data.json"

and I want to map thru this data:

render() {
  return (
     data.map((item) => (
       // Ofc it won't work if I just put {item.image} in src,
       // because we need to import image before use it
       // that's why I'm trying to use require
       <img src={require(item.image)} />
     ))
  )
}

But it won't work. How can I use images, which local patch is specified in json data for create-react-app?

Please, note: app should NOT be ejected.

WebArtisan
  • 3,996
  • 10
  • 42
  • 62

3 Answers3

0

Check if create-react-app has Webpack configured to bundle images (.png check webpack.config.js) out of the box. If so, it seems like you're only missing a relative path starting like this './assets/anotherpic.png' if assets is in the same folder as the component.

spakmad
  • 880
  • 6
  • 15
  • create-react-app has webpack files only for ejected apps. – WebArtisan Aug 02 '18 at 20:31
  • `assets/anotherpic.png` is not a relative path by Webpacks definition. it may be looking for the file in your modules. https://webpack.js.org/concepts/module-resolution/#relative-paths – spakmad Aug 02 '18 at 20:40
0

Make sure that load from require right paths. Your photos doesn't located assets/anotherpic.png , maybe you should load from absolute path ./assets/anotherpic.png

xargr
  • 2,788
  • 1
  • 19
  • 28
0

If you use Webpack v4, have you try to use require.context()?

It allows you to pass in a directory to search, a flag indicating whether subdirectories should be searched too, and a regular expression to match files against.

See the source into the webpack documentation

Your code can be something like that :

data.json

[
  {
    "id": 1,
     "image": "somepic.png"
  },
  {
    "id": 2,
     "image": "anotherpic.png"
  }
  // similar data goes there
]

file.js

const pathToAssets = require.context('assets/');

...

render() {
  return (
     data.map((item) => (
       <img src={pathToAssets(item.image)} />
     ))
  )
}
Jérémie Boulay
  • 400
  • 4
  • 13