ThirdGhostHand
ThirdGhostHand

Reputation: 397

Passing an image dynamically as props to child component

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!

Upvotes: 0

Views: 503

Answers (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).

Upvotes: 2

Related Questions