0

Here is usually how an image is imported in react

import React, { Component } from "react";
import smallclear from "../images/small/smallClearLaptop.jpeg";

class Images extends Component{
  constructor(props) {
    super(props);
  }
  render(){
    return(
     <div>
      <img src={smallclear}></img>
     </div>
 );

}
}

Instead of directly referring to the image as the name itself I want to use props to build the name using strings so in the render I want to do:

  render(){
   // this prints smallclear
   imgName= this.props.size + this.props.material; 
    return(
     <div>
      <img src={imgName}></img>
    </div>
 );
}


The image is not appearing when I do it the second way. I'm only doing this way because I have to display the image conditionally and that will require a lot of if statements. Is there any way to refer to the imported images without directly naming them in the src?

Colin Kawai
  • 3
  • 1
  • 5
  • If you do it like this then the images don't get bundled; this means that a) they need to be inside your `public` folder and b) you need to provide the full path, probably best as something like `src={"/images/" + imgName}` –  Jun 11 '20 at 21:07
  • Yeah I ended up using the full path. I changed simplified the folder structure and did src={require("../images/" + imageType + ".jpeg")} – Colin Kawai Jun 11 '20 at 21:47
  • Likely a dupe then: [How to give Image src dynamically in react js?](https://stackoverflow.com/questions/54033765/how-to-give-image-src-dynamically-in-react-js) –  Jun 11 '20 at 22:23
  • Another way you can do is upload the relevant images to a static cloud (like S3 or Azure blob) and use the link as the src value. this saves you from having to migrate all to images to your production server when deploying. – Shmili Breuer Jun 12 '20 at 05:17

0 Answers0