Program-Me-Rev
Program-Me-Rev

Reputation: 6624

How to dynamically include a module in React Native

I am trying to dynamically do a dynamic import import (this.props.myImportModulePath) but I get :

Error: TrasformError index.js: index.js:Invalid call at line 12: import(_this.props.myImportModulePath), js engine: hermes  

I am not sure that this is the way to go about it, but what I am trying to get is to get import ToastExample from './ToastExample'; dynamically.

Below is how I go about it.

Thank you all in advance.

import React, {Component} from 'react';
import {AppRegistry, Text} from 'react-native';

import {name as appName} from './app.json';

class HelloWorld extends Component {

    constructor(props) {
        super(props);

        this.state = {
            OtherComponent: React.lazy(() => import (this.props.myImportModulePath))
        }
    }

    render() {
        return (
            <Text>HELLO World</Text>
        );
    }
}
AppRegistry.registerComponent(appName, () => HelloWorld);  

Please note that this works when I change

OtherComponent: React.lazy(() => import (this.props.myImportModulePath))

into

OtherComponent: React.lazy(() => import ('./myImportModule')),

that is, passing the path directly as a string './myImportModule' instead of passing it as a prop value this.props.myImportModulePath

Thank you all in advance.

Upvotes: 4

Views: 1250

Answers (2)

Lenoarod
Lenoarod

Reputation: 3610

I think you want to according to some condition to import some components. I think you can do it as the following:

componentDidMount() {
      const { path } = this.props;
      // here your path is your full, if you use relative path, you have to add 
      // prefix
      // here you can add your condition
      import(`${path}`)
      .then(module => this.setState({ module: module.default }))   
   }

render() {
  const { module: Component } = this.state; 
  <View>
  {Component && <Component path='./Footer' />} 
  </View>
}



if you want to use flatlist, your can try use it columnWrapperStyle style.

Upvotes: 0

Andus
Andus

Reputation: 1731

I think you cannot use import dynamically but you can dynamically change which component you are calling instead, syntax is as mentioned in this post: React - Dynamically Import Components

Upvotes: 2

Related Questions