Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to dynamically import a module in Javascript / ReactJs / React Native

I would like to dynamically import a module from a path importPath set via Props.

var importPath;

class MainComponent extends Component {
    state = {}
    render() {
        // Set var importPath = "path_to_module here;"
        // importPath = this.props.myModulePath
        return (
            <ComponentToImport myComponentPath="./ToastExample" />);
    }
}

export default MainComponent;

Then :

class ComponentToImport extends Component {
    ToastExample: (async () => {
        await import (this.props.revPath)
    })()

    async sayHiFromJava() {
        this.state.ToastExample.showJ('Awesome', ToastExample.SHORT);
    }

    render() {
        return (<ToastExample />);
    }
}

How can I go about this?

Thank you all in advance.

How do I attach ToastExample in import ToastExample from importPath; to await import("importPath"); so that I can return(<ToastExample />);

UPDATE

I have tried :

class ComponentToImport extends Component {
    ToastExample: (async () => {
        await import (this.props.revPath)
    })()

    async sayHiFromJava() {
        this.state.ToastExample.showJ('Awesome', ToastExample.SHORT);
    }

    render() {
        return (<ToastExample />);
    }
}

but I get the error :

error: bundling failed: index.js: index.js:Invalid call at line 28: import(_this.props.myComponentPath)
like image 639
Program-Me-Rev Avatar asked Jun 17 '26 01:06

Program-Me-Rev


1 Answers

I guess this is the way:

import("importPath").then(() => {
    // your code
});

or

await import("importPath");

// your code

see more here https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import

like image 85
crtag Avatar answered Jun 18 '26 14:06

crtag



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!