0

In my react native app, I currently have the following import:

import { IMG_ARABIC_FLAG, IMG_ENGLISH_FLAG } from '../assets/images/index';

If I have a dynamic string, say 'IMG_ARABIC_FLAG', is there a way to do something like eval('IMG_ARABIC_FLAG') to import the flag from the /index module instead?

The list of languages is stored in an external JSON file, and the image constant is a resource containing the actual image. Because I am getting the flag name as string, I need a way to include the flag image using the string value.

4
  • What CertainPerformance said, and if you don’t want to allow access to any old property/import everything for whatever reason, const flags = new Map([['IMG_ARABIC_FLAG', IMG_ARABIC_FLAG], ['IMG_ENGLISH_FLAG', IMG_ENGLISH_FLAG], …]). The repetition is unfortunate, but kind of necessary. Commented Dec 10, 2019 at 3:36
  • I was trying to avoid repetition as well. It is interesting that I can just create an object with the mapping and load it. the issue again is, the JSON list is included in external file, hence we are looking for ways to add/remove records from JSON file directly, if we have to modify the object/array list everytime we change the JSON file, it kinds of defeat the purpose. Commented Dec 10, 2019 at 3:37
  • 1
    Can you separate the images into more modules by type, so you can import * from '../assets/images/flags' instead? Commented Dec 10, 2019 at 3:43
  • this make more sense to avoid the full import Thanks. I wish there was a way to initialise the import constant from string :-) Commented Dec 10, 2019 at 3:45

1 Answer 1

2

You can import the whole namespace object via import *, and then access the IMG_ARABIC_FLAG value on the object via bracket notation:

import * as flags from '../assets/images/index';
// ...
const selectedProp = 'IMG_ARABIC_FLAG';
const selectedFlag = flags[selectedProp];
Sign up to request clarification or add additional context in comments.

3 Comments

I had the import * in mind, however If i just do star, then will it not include all image files which is huge in numbers. I was looking for a way to just call one import dynamically.
I think that regardless of whether the consuming module uses a single one of the named imports, or uses the whole namespace, the whole namespace will still be loaded and put into memory regardless, right? The entire module code in /index will run anyway.
I didn't know that, I always thought that by declaring the import it would just load what is declared in import.

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.