mevrick
mevrick

Reputation: 1045

How to dynamically import images in create-react-app

I am trying to pass a locally stored image name to a component via props. The problem is

<img src={require(`../assets/img/${iconName}.svg`)} />

is not working. I have bootstrapped the project using create-react-app. The component looks like this:

import React from 'react';

import best from '../../assets/img/best.svg';
import cashback from '../../assets/img/cashback.svg';
import shopping from '../../assets/img/shopping.svg';

const Card = ({iconName}) => {

    return (
        <>
            <img alt="icon" src={require(`../assets/img/${iconName}.svg`)} />
        </>
    );
};

export default Card;

SVGs are failing to load. Even if I write something like:

<img src={require('../assets/img/best.svg')} />
<img src={`${iconName}`} />

it doesn't work. Can this be an issue with webpack loader in CRA?

Upvotes: 1

Views: 962

Answers (1)

Kamil Janowski
Kamil Janowski

Reputation: 2025

Because those are SVGs, I imagine, there's a static number of images you might want to display. At this point you might need to import them all in the beginning. Depending on the tools that you're using around react the dynamic loading of data may or may not work. Your approach definitely would not work for instance with Next.JS (a framework around react).

so I would suggest just loading them all, putting into a map and using that instead of the dynamic require.

import React from 'react';

import best from '../../assets/img/best.svg';
import cashback from '../../assets/img/cashback.svg';
import shopping from '../../assets/img/shopping.svg';

const icons = Object.freeze({best, cashback, shopping});

const Card = ({iconName}) => (<img alt="icon" src={icons[iconName]} />);

export default Card;

Upvotes: 1

Related Questions