Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I dynamically import images in React?

Have seen a couple of answers online but there are no clear explanations and the solutions don't work. So this is what I am trying to do:

  • I have a folder of MANY images (thousands) - currently it is saved under src/assets/images folder
  • Given a list of images for example as input, I want to render these images dynamically. And not import all because it would be impossible given the insane number of images

This is my current way of implementing it (which does not work):

// for example
const imageList = ['img1', 'img2', 'img3' /*...so on */]

const getImagePath = (image) => {
  return `../assets/images/${image}.jpg`
}

function ImagesPage() {
  return (
    <>
      <p>Below should show a list of images</p>
      {imageList.map((img) => {
        return <img src={require(getImagePath(img))} />
      })}
    </>
  )
}

From what I read online, this has something to do with the way webpack works, and this will only work if the exact string path is input into the require:

// This works:
<img src={require('../assets/images/img1.jpg')} />

// But all these will not work:
<img src={require(getImagePath(img))} />

const img = 'img1.jpg'
<img src={require(`../assets/images/${img}`)} />

Any idea how I can get this dynamic importing of images to work in the scenario I described above? I think this post will be quite helpful to the others searching for an answer too.

like image 615
Daryll Avatar asked Jun 04 '20 10:06

Daryll


People also ask

How do I use dynamic import in React?

In React, dynamically importing a component is easy—you invoke React. lazy with the standard dynamic import syntax and specify a fallback UI. When the component renders for the first time, React will load that module and swap it in.

How do I import an image into React?

To import and use an image in a React component: Import the local image, e.g. import MyImage from './thumbnail. webp'; . Pass the imported image to the src prop on the img element. For example, <img src={MyImage} alt="horse" /> .

How can change dynamic image in React JS?

It has to be a string literal. @backslashN this does work (at least locally), if needed you can use "./img/"+img. code+". jpg" - React will convert it to the string before importing it.

How do I use image URL in React?

To display an image from a local path in React: Download the image and move it into your src directory. Import the image into your file, e.g. import MyImage from './thumbnail. webp' . Set the src prop of the image element to the imported image, e.g. <img src={MyImage} alt="horse" /> .


2 Answers

Adding .default will do the trick

<img src={require(`../../folder-path/${dynamic-filename}.png`).default} />
like image 142
mleister Avatar answered Oct 08 '22 09:10

mleister


TLDR;

// All of these works

const fileNameExt = 'foo.jpg'
<img src={require('../images/' + fileNameExt)} />
<img src={require(`../images/${fileNameExt}`)} />

const fileName = 'foo'
<img src={require('../images/' + fileName + '.jpg')} />
<img src={require(`../images/${fileName}.jpg`)} />

// These does not work:

const myPathVariable1 = '../images/' + 'foo' + '.jpg'
<img src={require(myPathVariable1)} />

const myPathVariable2 = '../images/' + 'foo.jpg'
<img src={require(myPathVariable2)} />

You can require dynamically with expression.

File names:

const imageList = ["img1", "img2", "img3", ... ]

And to render at UI (add directory path and the extension inside require):

{
  imageList.map(img => {
    return <img src={require("../assets/images/" + img + ".jpg")} />
  })
}

Why it works?:

Webpack can understand this expression, by generating context about directory and extension, and can load all the matching modules.

like image 32
Ajeet Shah Avatar answered Oct 08 '22 11:10

Ajeet Shah