Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save falcon11/00807916901836b31fafa1f3444d3998 to your computer and use it in GitHub Desktop.
Save falcon11/00807916901836b31fafa1f3444d3998 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>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment