Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React imported image within a function

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 ?

like image 433
Franck Boudraa Avatar asked Feb 06 '26 22:02

Franck Boudraa


1 Answers

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} />
like image 74
The Reason Avatar answered Feb 09 '26 01:02

The Reason