Skip to content

Instantly share code, notes, and snippets.

@adyontech
Last active June 28, 2021 17:57
Show Gist options
  • Save adyontech/0ed32d46b70ed2f4037dbbbbc1477edc to your computer and use it in GitHub Desktop.
Save adyontech/0ed32d46b70ed2f4037dbbbbc1477edc to your computer and use it in GitHub Desktop.
A simple trick to dynamically import components in react.

AsyncLoadFile.jsx

import React, { Component } from 'react';

export default function asyncComponent(importComponent) {
    class AsyncComponent extends Component {
        /**
        * @constructor
        * @desc Represents AsyncComponent component
        * @param props Properties passed from parent component
        */
        constructor(props) {
            super(props);

            this.state = {
                component: null
            };
        }

        // Returns the needed component markup
        // Can be a single child component or null or false
        render() {
            const C = this.state.component;

            return C ? <C {...this.props} /> : null;
        }

        // Called after render method
        // Enables DOM manipulations or data fetching operations
        // DOM interactions should always happen here
        async componentDidMount() {
            const { default: component } = await importComponent();

            this.setState({
                component: component
            });
        }
    }
    return AsyncComponent;
}

use of following component

import AsyncComponentLoad from 'AsyncLoadFile.jsx';

const someComponent = AsyncComponentLoad(() => import('theComponent'));

<Switch>
    <Route
        exact
        path={`${prependUrl}`}
        component={Home} />
</Switch>
@emibcn
Copy link

emibcn commented Jan 20, 2021

Maybe you want to check it here:
https://github.com/emibcn/covid/blob/master/app/src/asyncComponent.jsx

I used your code (used here) and added the full module async loader (used here).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment