4

I meet a weird problem. If I set a variable direclty with a value like this "const myString = 'someWord';" that work but if I take the value from a variable like this "const myString = someVariable;", that doesn't work, and if I set the value on a conditional block that doesn't work too.

So, work:

    var jsonName = 'tramwayen';
    const pathex = require('../assets/JSON/' + jsonName);
    var json = JSON.parse(JSON.stringify(pathex));

doesn't work:

    var jsonName = variable;
    const pathex = require('../assets/JSON/' + jsonName);
    var json = JSON.parse(JSON.stringify(pathex));

doesn't work:

    var jsonName = '';
    if (condition) {
       jsonName = 'tramwayen';
    }
    const pathex = require('../assets/JSON/' + jsonName);
    var json = JSON.parse(JSON.stringify(pathex));

I really don't understand.

I have this error : "Invalid call at line 41: require('../assets/JSON/' + jsonName2)"

2
  • Where is the jsonName2 coming from? Commented Apr 25, 2019 at 14:51
  • It's jsonName, I just have other name on my real code Commented Apr 25, 2019 at 15:40

2 Answers 2

7

Most JS bundlers cannot handle dynamic require imports. You might want to load all of the files, and put them in an object:

let data = {
    tramwayen: require('../assets/JSON/tramwayen.json'),
    something: require('../assets/JSON/something.json'),
    // and so on
};

And use the data object to retrieve the data you need.

Sign up to request clarification or add additional context in comments.

1 Comment

I'm already trying to take the whole json, the file is named tramwayen.json, but the extension .json is not necessary. If I put it on, it crashes.
0

From what I read while doing some research, it seems impossible to made a require dynamically. In react native require should be static. But there are some solutions to avoid this issue.

Here is mine, I put all data of my differents Json on one single json, and I dynamically choice wich part of the data I want to get.

I can also, put all the static require on an object, and choose dynamicaly wich require I want to get.

solution 1:

    const id = window.currentPI;
    const json = require('../assets/JSON/mainData.json');
    const nbreOfPix = json[`${id}`].preData.numberOfPictures;

solution 2:

const IMAGES = {
    tramwayen: require('../assets/CtrlPI/PHOTO_articles/008_02_Img.png'),
    tramwayen2: require('../assets/CtrlPI/PHOTO_articles/HC002_04_Img.png')
};

getImage = (name) => {
    return IMAGES[name];
};

Comments

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.