简体   繁体   中英

Import image from json source (create-react-app)

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.

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.

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

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)} />
     ))
  )
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM