skip to Main Content

I would like to load images dynamically from an images folder.
Names in the folder like {company_name}.png. The names are stored in a json file along with other company data like name, type, etc.

e.g.:
name: meta
logo: "./images/meta.png"

Is there any way to dynamically load these images like require(changing variable based on the json logo string).


I found some solution online like:
https://stackoverflow.com/a/52598171/7990652

But all the other things are build around the json structure to load all the other data.
Is there any way to load everything from a folder one by one based on the provided logo link in the json?


I also tried to look around for a solution with babilon require all plugin, but I found nothing about that.

P.S. I know there are sevaral threads about this question, but in almost all the threads someone asking "what about if I want to load 100-1000 images?". That is the case with me too, I would like to load a lot of images, not just up to 10-20 which is complately okay with static .js require list.

2

Answers


  1. No, unfortunately your question is a duplicate of the others you have found, and it is not possible to use require dynamically, no matter how many times you want to do it.

    If you can break up the images into multiple components, you can conditionally load those components. But require must be called with a fixed string.

    Login or Signup to reply.
  2. Dynamically loading local assets at run-time including images is not supported within React Native.

    In order to use static assets (images, fonts, documents,…). All assets must be bundled at compile-time with your app.

    Attempts to load assets dynamic at run-time without pre-bundled at compile time will cause the app to crash.

    Bundle all images you need at compile-time then use image reference in memory at run-time.

    const staticImages = {
      image_01: require("./path/to/image_01.png"),
      image_02: require("./path/to/image_02.png"),
      image_03: require("./path/to/image_03.png"),
      // ... more images
    };
    
    

    Define this object containing images reference globally and make sure it is executed as early as possible when the app is initializing.

    Later access any image reference as below:

    
    <Image source={staticImages[IMAGE_REFERENCE_NAME]} />
    
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search