0

In my parent component, I'm receiving an object from an API that I later inject an image into as a key/pair value. I then pass that object off to a child component to be rendered, and I have attempted to follow this post to do so:

Load images based on dynamic path in ReactJs

However, despite copying webpack's necessary image import format, I'm still receiving this error.

Error: Cannot find module '../images/test.jpg'

That path can be used directly in the component just fine... but when imported as such... things break.

Here is the code from the child component:

const WorldInfo = (props) =>  {
    return props.world ? (
        <div className={props.className}>
            <h1>{props.world.map}</h1>
             <img src={require(`${props.world.image}`)}/>
        </div>
    ) : 
        null
}

Thanks for looking friends!

isherwood
  • 58,414
  • 16
  • 114
  • 157
ThirdGhostHand
  • 377
  • 5
  • 19
  • 1
    Using them without the require should work? – Jesse Schokker Oct 30 '19 at 18:18
  • `that I later inject an image into as a key/pair value` is a strange thing to say about JavaScript. Can you provide an example of how you do this. – Reactgular Oct 30 '19 at 18:18
  • 1
    Instead of passing a full path (relative or absolute), pass only the last name (test.jpg). WebPack will detect a dynamic require and will bundle all the files inside the folder, like so: `require('../images/' + props.world.image)`. I'm not sure if this is your problem, but that's how WebPack works. – Jorge Fuentes González Oct 30 '19 at 18:19
  • 1
    @isherwood but maybe the image is not served as an HTTP request. It only forms part inside the project as an asset, like you do with `.json` for example. For this you need an image loader actually, which will convert the image to a base64 data URL. – Jorge Fuentes González Oct 30 '19 at 18:20
  • @Reactgular When I say inject, all I mean is this, ```map.data[1].result.image = "../images/testPlanet.jpg"``` – ThirdGhostHand Oct 30 '19 at 18:23
  • @JorgeFuentesGonzalez had the answer! Now my injection looks like this, ```map.data[0].result.image = "testPlanet.jpg"``` and my reference in the child component looks like this `````` – ThirdGhostHand Oct 30 '19 at 18:24
  • 1
    Woah nice. If you don't mind, I'll create an answer for this :P – Jorge Fuentes González Oct 30 '19 at 18:25
  • Please do! Thanks! You're the man! – ThirdGhostHand Oct 30 '19 at 18:30

1 Answers1

2

Instead of passing a full path (relative or absolute), pass only the last name (test.jpg). WebPack will detect a dynamic require and will bundle all the files inside the folder, like so: require('../images/' + props.world.image).

Jorge Fuentes González
  • 11,568
  • 4
  • 44
  • 64