jolearn
jolearn

Reputation: 145

require() not working with variable - react native

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)"

Upvotes: 4

Views: 3740

Answers (2)

jolearn
jolearn

Reputation: 145

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];
};

Upvotes: 0

Tim VN
Tim VN

Reputation: 1193

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.

Upvotes: 7

Related Questions