Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

import file dynamically by variable - react native

I have a path.json file that contains the path of a component

// path.json

{
  "main": "./login/index.js",
  "paths": [
    {
      "name": "login",
      "path": "./login/index.js",
      "image": ""
    }
  ]
}

I want to load './login/index.js' file dynamically in react native and render this particular file

My current implementation

const MyComponent = createLazyContainer(() => {
  const componentPath = PathJson.main; // ./login/index.js
  return import(`${componentPath}`); //import error here @ line 7
});

export default MyComponent;

I am getting following error :

Invalid call at line 7: import("" + componentPath)

like image 897
Muhammad Iqbal Avatar asked Mar 06 '20 10:03

Muhammad Iqbal


1 Answers

What people have been telling you in the thread is correct but I'd like to add one possible solution. All the imports/require are resolved at compilation time and not at running time which you are trying to do. By the time you are running your app, if you haven't imported the files, you can't use them.

There is a workaround tho, assuming that you know all the files that you might in advance which is to do something like a factory:

   const possiblePaths = {
     'one': require('path/to/file/1),
    'two': require('path/to/file/2)
}

funtion(type){
    return possiblePaths[type]
}

And then you use it somehow like:

render(){
   const MyComponent = function('one')

  return <MyComponent/>
}

This is more or less pseudo code and my not work right away, but hopefully yo get the idea. You need to store a reference to each of the imports you might need and then dont use the import, use the reference that was created for you at compilation time.

like image 183
sebastianf182 Avatar answered Sep 23 '22 04:09

sebastianf182