0

I'm using the create-react-app template.

In one of my components, I am importing the path to several images like so.

import iconAvatar from '../img/icon-avatar.png';
import iconHome from '../img/icon-home.png';
import iconVendor from '../img/icon-vendor.png';

Now let's say I have a variable like this, which determines what image to use.

let imageType = "avatar"; // or "home", or "vendor", etc.

I want to dynamically render out the proper image based on the value of imageType (without having to use a convoluted if-else structure)

Something like the following (except that it won't work)

<img src={"icon"}{imageType}/>

How do I do this?

Cog
  • 1,545
  • 2
  • 15
  • 27
  • All you need to do is concatenate, but you might consider using an object containing all images, rather than three independent variables – CertainPerformance Nov 15 '18 at 02:16
  • What exactly is the output HTML supposed to look like? There is no `type` attribute on the `img` tag that I am aware of or the MDN lists as being available. – Matthew Herbst Nov 15 '18 at 02:20

2 Answers2

2

If all of your file names follow that standard you can just use string concatenation.

<img src={'../img/icon-' + imageType + '.png'} />

or even cleaner with string interpolation..

<img src={`../img/icon-{$imageType}.png`} />

Edit: When using webpack you must use require and when using require string concatenation does not work, however string interpolation still works. So..

<img src={require(`/img/icon-{$imageType}.png`)} />

See this answer for more information.

fqhv
  • 1,191
  • 1
  • 13
  • 25
0

You have a few options available:

First using an object as suggested by @CertainPerformance

const images = {
  avatar: require('../img/icon-avatar.png'),
  home: require('../img/icon-home.png'),
  vendor: require('../img/icon-vendor.png')
}

<img src={images[imageType]} />

Or you can use a switch / if statement

switch (imageType) {
  case 'home': return <img src={iconHome} />;
  case 'avatar': return <img src={iconAvatar} />;
  case 'vendor': return <img src={iconVendor} />;
}
dotconnor
  • 1,736
  • 11
  • 22
  • Thanks for your answer! I'm going with @fqhv's solution with template literals as it's a bit cleaner. – Cog Nov 15 '18 at 17:56