'How to pass an image as a prop in Typescript

I have just started to use Typescript and got an issue, possibly a basic.

I am trying to pass some images as props by using following code. And, I am getting the result of attached image. But, it does not display the images, which are passed as props.

I assume the relevant type for images, that I have used is wrong, but I could not find a way to rectify that error. I was just trying by replacing some types for the images, as per my understanding.

interface Props {
  thumbnailHeading: string;
  playBtn: string | undefined;
  thumbnail: string | undefined;
}

export const DisplayBox = memo(
  (props: Props): JSX.Element => {
    return (
      <div className="grid-container">
        <div className="box">
          <img className="samllImage" src={props.playBtn} />
          <img className="largeImage" src={props.thumbnail} />
          <div className="content">{props.thumbnailHeading}</div>
        </div>
      </div>
    );
  },
);

This is how I assigned related props, defined by above code.

<DisplayBox
   thumbnailHeading="Sample Text Title"
   playBtn="./image_files/SmallImage.png"
   thumbnail="./image_files/LargeImage.jpeg"
/>

enter image description here



Solution 1:[1]

This is not an issue with TypeScript but they way you're importing or referring to the static image asset. When you're trying to include or import images or static assets, instead of directly sending the path, what you need to do is, import them first:

import SmallImage from "./image_files/SmallImage.png";
import LargeImage from "./image_files/LargeImage.jpeg";

And then you pass on the variables:

<DisplayBox
   thumbnailHeading="Sample Text Title"
   playBtn={SmallImage}
   thumbnail={LargeImage}
/>

This is because the code is compiled and assets are compressed by WebPack or whichever bundler that you're using. Also, make sure to do the same approach for any static assets that you're importing inside the src directory.

Solution 2:[2]

interface Props {
  tab?: string,
  image?: JSX.Element,
}
    
const DisplayBox =(props: Props): JSX.Element => {
  return (
    <div className="grid-container">
      <div className="box">
        {props.image} />
      </div>
    </div>
  );
}

export default DisplayBox; 
      
const app=(): JSX.Element=>{
  return (
      <DisplayBox  image={<img alt="" src={image.jpg}/>}/>
  );
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Praveen Kumar Purushothaman
Solution 2 Josef