react-import

Lazily import React components

Usage no npm install needed!

<script type="module">
  import reactImport from 'https://cdn.skypack.dev/react-import';
</script>

README

react-import

NPM version Downloads Dependency status Dev Dependency status

A wrapper for lazy import of React components

Installation

npm install --save react-import

Usage

Basic usage:

import React, { PureComponent } from 'react'
import Import from 'react-import'

class MyComponent extends PureComponent {
  // ...

  render() {
    // ...
    return (
      <>
        <Import
          component={import('./another-component')}
          some="prop"
          another={1}
        />
      </>
    )
  }
}

You can also pass an import function as load prop which will be called once the Import component is mounted.

    // ...
    return (
      <Import
        load={() => import('./another-component')}
        some="prop"
        another={1}
      />
    )
    // ...

Additional props can be used: loading specifying the React component which should be displayed while the component is loading, and onLoad function called once the component is loaded, error specifying the React component which should be displayed on error, and onError function called on error.

    // ...
    return (
      <Import
        component={import('./another-component')}
        loading={<div>wait...</div>}
        error={<div>error!</div>}
        onLoad={() => console.log('component has loaded!')}
        onError={() => console.error('component has failed to load :('))}
      />
    )
    // ...