Back to home

Example Code
React Dynamic Imports main image

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.

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

Here is the full code example:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 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.

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 workingoutloud.dev, Den Dribbles and LandPad .

Related articles


1,200+ PEOPLE ALREADY JOINED ❤️️

Get fresh posts + news direct to your inbox.

No spam. We only send you relevant content.