0

This code that you can see works if the project was created with create-react-app but instead it throws the following error "require is not defined"

<img src={require(`../Media/${imagen}.jpg`)} alt={textoImagen}/>

If anyone knows a way to receive the images in a similar way please let me know

vsync
  • 118,978
  • 58
  • 307
  • 400
Aldebaran
  • 11
  • 1

1 Answers1

0

You're going to have to use static imports, but this requires some trickery around getting them to work with a dynamic string as you need.

What you do is import everything in the folder line by line and then you reference those variables using a map. It's quite cumbersome. There are nicer ways to do this in Vite for example where you have wildcard require's or if you are in an ejected create-react-app setup where you can modify the webpack config.

Create a new file inside of Media folder called index.js and export every image from it. I have just used some random names by way of example.

// These names after the `as` must match the expected string contained within `imagen` for this image.

export { default as image1 } from './image1.jpg'
export { default as image2 }  from './image2.jpg'
export { default as image3 }  from './image3.jpg'
export { default as image4 }  from './image4.jpg'

Now in your file where you need to use them do:

import * as images from '../Media'

// ...

<img src={images[imagen])} alt={textoImagen}/>

adsy
  • 8,531
  • 2
  • 20
  • 31