I have a hand full of json objects I need to load into a react native app. I couldn't find much documentation on how import sample from '../data/Sample.json'; imports. I will only need to load 1 file depending on what the user selects and I am not sure if I just import all 12 files (1mb total) if that will be more impactful on performance than I need. Is there a way I can selectively load a json file depending on state or user input?
1 Answer
Put the links to the JSON files in an array and use require() as needed:
links = [
'link_to_file_1.json',
'link_to_file_2.json',
// and so on...
];
loadMyFile = (index) => { // Call this function with required index of list
if (index)
{
let fileUrl = require(links[index]);
// parse file, perform required actions ...
}
}
require()for importing it? You could set a variable string to the file you need programmatically and callrequire(pathToRequiredFile)to load it. However,requirecaches your files for future use, so keep that in mind of you use it.