Dynamic loading of react components

Basically it boils down to pre-creating all the chunks you will ever need. Then you just need a way to dynamically refer to them. Here’s the solution I based mine on:

http://henleyedition.com/implicit-code-splitting-with-react-router-and-webpack

and here’s what I do since I don’t use React Router (side note: i dont find it to be a good match for redux or animations):

//loader:
{
  test: (folder)\/.*\.js,
  include: path.resolve(__dirname, 'src')
  loader: ['lazy?bundle', 'babel']
}

//dynamic usage within React component:
const My_COMPONENTS = {
   ComponentA: require('./folder/ComponentA'),
   ComponentB: require('./folder/ComponentB'),
}

class ParentComponent extends React.Component {
    componentDidMount() {
        My_COMPONENTS[this.props.name](component => this.setState({component}));
    } 
    render() {
       return <this.state.component />;
    }
}

So the result is you are dynamically rendering a component, but from a static pre-determined set of possibilities–all while, only sending no more to the client than the chunks the visitor is actually interested in.

ALSO, here’s a component I have that does this well:

import React from 'react';
import Modal from './widgets/Modal';

export default class AjaxModal extends React.Component {
  constructor(props, context) {
    super(props, context);
    this.state = {
      Content: null
    };
  }

  componentDidMount() {
    if(this.props.show) {
      this.loadContent();
    }
  }

  componentWillReceiveProps({show}) {
    if(show && !this.state.Content) {
      this.loadContent(1200); //dont interfere with animation
    }
  }

  loadContent(ms=0) {
    setTimeout(() => {
      this.props.requestLazyBundle(({default: Content}) => {
        this.setState({Content});
      });
    }, ms);
  }

  render() {
    let {Content} = this.state;

    return (
      <Modal title={this.props.title} {...this.props} loading={!Content}>
        {Content ? <Content /> : null}
      </Modal>
    );
  }
}

pass pass an async require bundler function as this.props.requestLazybundle, like this:

render() {

  let requestLazyBundle = require('bundle?lazy&name=AnotherComponent!../content/AnotherComponent');

  return (
    <AjaxModal title="Component Name" {...props} requestLazyBundle={requestLazyBundle} />
  );
}

Leave a Comment