🎉 I'm releasing 12 products in 12 months! If you love product, checkout my new blog workingoutloud.dev

Back to home

React Dynamic Imports

    Example Code

    The key action happens by using React's componentDidMount lifecycle method and component state, although the application of when to import can be used anywhere when required.

    componentDidMount() { import('components/ComponentB').then((module) => this.setState({ module: module.default }) ); }

    Here is the full code example:

    import React, { Component } from "react"; /** * Dynamically load ComponentB. * * @class ComponentA * @extends {Component} */ class ComponentA extends Component { constructor(props) { super(props); this.state = { module: null, }; } /** * On mount, dynamically fetch ComponentB. * * @memberof ComponentA */ componentDidMount() { import("components/ComponentB").then((module) => this.setState({ module: module.default }) ); } /** * Render ComponentA component. * * @memberof ComponentA * @returns {ComponentA} component Basic div with dynamically loaded child */ render() { const { module: ComponentB } = this.state; return ( <div className="component-a"> {ComponentB && <ComponentB {...this.props} />} </div> ); } } export default ComponentA;

    Hello is a series that is about short, sharp examples. Read more on this series to find small gems to add your toolset.

    Personal image

    Dennis O'Keeffe

    @dennisokeeffe92
    • Melbourne, Australia

    Hi, I am a professional Software Engineer. Formerly of Culture Amp, UsabilityHub, Present Company and NightGuru.
    I am currently working on Visibuild.

    1,200+ PEOPLE ALREADY JOINED ❤️️

    Get fresh posts + news direct to your inbox.

    No spam. We only send you relevant content.

    React Dynamic Imports

    Introduction

    Share this post