2

How to dynamically render/ import images in react / typescript?

I'm using Typescript with React.

Following is what I want to achieve.

but this is not working. It is not resolving the expression { 'assets/icons/' + media + '.svg'} .

    <div className="medias">
        MEDIAS.map((media) =>
        (<img src={ 'assets/icons/' + media + '.svg'} />)
        )
    </div>



This is what I've tried.

const Medias = async () => {
  return (
    <div className="medias">
      {await Promise.all(
        MEDIAS.map((media) =>
          import(`assets/icons/${media}.svg`).then((v) => v.default)()
        ).map((item) => <img src={media} />)
      )}
    </div>
  );
};

export default Medias

I want to dynamically import and render images based on the above logic.

In angular or vue this can be achieved easily inside templates. But here in react it seems like not working.

But seems like it is not working.

Is there a work around?

1
  • I think what you did is right! Commented Apr 18, 2021 at 19:18

1 Answer 1

1

For local image files instead of importing every image while mapping over them, you can make a separate file and add all the imports in that file and make an object of all the images, and export that object to use anywhere dynamically. I have created an example on the sandbox here you can check this out for your case.

import img1 from "./assets/1.jpeg";
import img2 from "./assets/2.jpeg";
import img3 from "./assets/3.jpeg";

export const imagesPath = {
  img1: img1,
  img2: img2,
  img3: img3
};

Now, this can be used to dynamically use the images as shown in the code snippet below.

Medias.map((media) => (
        <img
          src={imagesPath[media]}
          alt="Dynamic Image"
          key={media}
        />
      ))

To see the working example checkout the code sandbox link given above.

Sign up to request clarification or add additional context in comments.

4 Comments

Doesn't necessarily need to be in a seperate file but this is correct. Also, creating an array instead of an object is cleaner const images = [img1, img2, img3].
@moritzsalla Yes, no need for a separate file but I think it's good to have one if there are a lot of local assets to export. And with the array how are we going to dynamically fetch the image with its name as it can be on any index in the array?
Don't quite understand what's meant by "dynamic". images.map((image, i) => <img src={image} key={i}/>) will work fine in case of mapping an array const images = [img1, img2, img3]. We can access a specific image like so <img src={images[2]} />.
@moritzsalla As I understand from the question the user doesn't want to display all the pictures he/she wants to display only the pictures which are given in the media array and the array contains only the images names and that can be random in any order not the same order as you are trying to define in an array. So we can't use their index to get the same image we have to get the same image as the name given in the media array here.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.