1

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?

1 Answer 1

1

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;

Sign up to request clarification or add additional context in comments.

1 Comment

yeah, understanding how your framework works on a low level really helps :P if you're building a single page app, then once your code is compiled, there are no more imports/requires. This makes the dynamic imports rather difficult

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.