3

So what I an trying to do is to read image-src from a JSON file. In the JSON file I have something like this:

{
   posts:[
           {"img": "../images/a.png"},
           {"img": "../images/b.png"},

           //and more... 
         ]

}

Then I am trying to use these paths as image src in react:

import data from '../posts.json';

<img src={require(data.posts[0].img)}/>

This does not work, I get this error: Error: Cannot find module ".". Is there a way I can make this work?

Sarmad S.
  • 241
  • 2
  • 4
  • 12

1 Answers1

0

You shouldn’t use require there.

<img src={ data.posts[0].img }/>
Ben West
  • 4,398
  • 1
  • 16
  • 16
  • I dont get any error with your solution, but the image does not show up. In the chrome debugger, I see that the path is written correctly, but no image is displayed, this has something to do with webpack. When using require with a static path it works, but not with dynamic path. – Sarmad S. Jul 01 '18 at 10:37