Maaz Ahmad Khan
Maaz Ahmad Khan

Reputation: 172

Unable to load images dynamically in react app

I have this component :-

const CollectionItem = ({ item }) => (
    <div className='collection-item'>
        <div
            className='image'
            style={{
                backgroundImage: `url(${item.imageUrl})`
            }} />
        </div>
    </div>
)

my images urls are like ../../assets/images/imageName.jpg

i have tried loading a an image in the css file associated with this component with this exact url. It is working with css, but not in jsx. Please help.

Upvotes: 0

Views: 443

Answers (1)

lanxion
lanxion

Reputation: 1430

Generally, how you load images in react is to import the image from the specified folder (webpack converts it into the correct source behind the scenes), and then to use that imported variable as the src of the image.

import imgSource from "../../assets/images/imageName.jpg";

const CollectionItem = ({ item }) => (
    <div className='collection-item'>
        <div
            className='image'
            style={{
                backgroundImage: `url(${imgSource})`
            }} />
        </div>
    </div>
)

EDIT In the cases where the import depends upon the props, you could simple dynamically import the image within the function itself:

const CollectionItem = ({ item }) => (
    import imgSource from `${item.imageUrl}`;
    <div className='collection-item'>
        <div
            className='image'
            style={{
                backgroundImage: `url(${imgSource})`
            }} />
        </div>
    </div>
)

In the case that it does not work, you can try using require instead

const imgSource = require(item.imageUrl);

Upvotes: 1

Related Questions