-2

I have a data file api that has bunch of images url stored locally

   const url =[
          { title:img1,
            img_src="./img/img1.png"
          },
          { title:img2,
            img_src="./img/img2.png"
          },
          { title:img3,
            img_src="./img/img3.png"
          }
      ]

And using react/redux I pass the url state as props to my react components.Next I want to display them in my components by using require

<img src=require(?)/>

What's the appropriate syntax here? I've used es6 template string ${this.props.urls.img_src} but it throws an error that it couldn't resolve the path. I've tried to require("./img/img1.png") just to test to rule out broken path and it worked. But still wouldnt work if you reference it using a prop.

Solution

After researching, and thanks to Rei Dien for the input, I now can use variables in require by using context require

<img src={require("./img/"+this.props.img_src)}/>

Ndx
  • 517
  • 2
  • 12
  • 29
  • use the new import. i believe it can take a variable, im not quite sure if require can take a variable. http://2ality.com/2017/01/import-operator.html – Rei Dien Sep 23 '17 at 23:51
  • Hey thank you for the reply. your answer sort of guided into finding the solution. I researched on require accepting variables, and it usually does but webpack only does static string dependencies, so it can't resolve the path. All to solve it I had to do [context require](https://stackoverflow.com/questions/31694346/webpack-can-not-require-variable-the-request-of-a-dependency-is-an-expression/33048000#33048000). – Ndx Sep 24 '17 at 14:30
  • oh i see you are using webpack then. glad to be of help :) – Rei Dien Sep 25 '17 at 10:59

2 Answers2

0

since require works in static mode during build process on node only so follow following steps.

1) take all image urls and store them in a javascript file so

//imageURLs.js

import image1 from "path_to_image_file_1";
import image2 from "path_to_image_file_2";
import image3 from "path_to_image_file_3";/**do like this for all images stored locally, image1, image2,.. are the image identifiers(title in your case) you would get in api call**/
export const urls = {image1, image2, image3};

//image usage file

read api for identifier and

import imageURLs from './imageURLs.js';
<img src={imageURLs[image_id_from_api]}/>
Shishir Arora
  • 5,521
  • 4
  • 30
  • 35
0

Since you passed the url in the props, you can do this :

this.props.url.map(n => {
 return (
   <img src={n.img_src}/>
 )
})

this will diplay all the images.

Freddy
  • 1
  • 1