3

I want to display dynamically an imported image within a function on React (create-react-app).

Code:

import React, { Component } from 'react';
import reactImg from './img/react.png';

export default class MyPage extends Component {

  renderImage(imageName) {
    return (
      <img src={imageName.toLowerCase()+'Img'} alt={techName} />
    );
  }

  render() {
    return (
      <p>
        {this.renderImage("React")}
      </p>
    )
  }
};

This render:<img src="reactImg" alt="React" />

Instead of what I want: <img src="./img/react.png" alt="React" />

How to display an imported image dynamically within a function please ?

Franck Boudraa
  • 123
  • 1
  • 2
  • 14
  • 1
    there's nothing dynamic here, you can directly pass './img/react.png' to your img tag. – Ji aSH Jan 08 '18 at 08:48
  • No this doesn't work with webpack imported image. If I just pass 'reactImg' to my img tag it renders `/static/media/react.8d679960.png` – Franck Boudraa Jan 08 '18 at 08:54

2 Answers2

2

Not sure if it what you are looking for, but here you go:

renderImage(imageName) {
  return (
    <img src={imageName.toLowerCase()+'Img'} alt={techName} />
              ^^^^^^^^^                ^^^
    // thats wrong concatenation bc your image path looks different
  );
}

Try this one instead of your:

<img src={`./img/${imageName.toLowerCase()}.png`} alt={imageName} />
The Reason
  • 7,705
  • 4
  • 24
  • 42
0
import reactImg from './img/react.png';
import meteorImg from './img/meteor.png';

renderImage(imageName) {
    let imageCode;

    switch(imageName) {
      case 'React':
        imageCode = reactImg; break;
      case 'Meteor':
        imageCode = meteorImg; break;
    }

    return (
      <img src={imageCode} alt={imageName} />
    );
  };

render(){
  return(
    <p>
      {this.renderImage("React")}
      {this.renderImage("Meteor")}
    </p>

This render: <img src="/static/media/react.8d679960.png" alt="React">

It works.

Franck Boudraa
  • 123
  • 1
  • 2
  • 14