0

I have a lot of images I need to use in my react app, so I don't want to import them one by one. To that end, I'm using reqiure(). However, while require works when used like this below:

return <img src={require("./images/lets_go.png")} />

if I store that path in a variable:

let v = "./images/lets_go.png";
return <img src={require(v)} />

I get Error: Cannot find module './images/lets_go.png'

Why won't it allow me to use the path stored in a variable (it's the exact same path) and how can I make it work?

Elliptica
  • 3,928
  • 3
  • 37
  • 68
  • 1
    I'm pretty sure it has to do with webpack not knowing how to handle dynamic imports like that. You might want to narrow down its search via partial imports. [SEE](https://stackoverflow.com/questions/56084683/cannot-find-module-assets-logo-png-at-webpackemptycontext-eval-at-src-co) – prismo Sep 12 '20 at 05:56
  • 1
    requie(variable) and require('xxx') looks like the same but it is different for webpack. When webpack see "require('xxx')" it will know 'xxx' is a constant but for "require(v)" it doesn't know what "v" is at that point. – chendesheng Sep 12 '20 at 07:27

2 Answers2

1

this will work using a 'Partial' require, where you give the path as text and and the image name can be the varible. the reason this is happening is related to how webpack is meant to handle static paths.

What we know works, (static image path):

<img src={require("./images/lets_go.png")} />

Trying to make the path a varible like this we found does not work

let v = "./images/lets_go.png";

<img src={require(v)} />

What will work when trying to make the path a varible

 let v = "lets_go.png";

    <img src={require(`./images/${v}`).default} />

Note that .default needs to be added at the end of the require as of may/2021 due to a error related to react scripts. this might be fixed and not needed if you're reading this in the future.

you'll need to store all your images in the same folder of course, but this lets you dynamically load high volumes ofimages in react/js without needing to manually import them all into the code.

0

Either you may import the image and bind it to src attribute like its done in create-react-app with the logo as follows:

import logo from './logo.png' // relative path to image 

class Home extends Component { 
    render() { 
        return ( 
            <img src={logo} alt={"logo"}/> 
        )  
    }
}

Or, if you used create-react-app cli to create your project then your public folder is accessible. Just create the images or assets folder in public and you may access it in jsx as follows:

public/images/ -> store images here

<img src="/images/home.png" /> -> use it like this in jsx
Peter
  • 10,492
  • 21
  • 82
  • 132