create-async-component
TypeScript icon, indicating that this package has built-in type declarations

2.0.0 • Public • Published

create-async-component

Bundlephobia Types Code coverage Build status NPM Version MIT License

npm i create-async-component

A factory function for creating asynchronous React components.

Quick Start

import * as React from 'react'
import createAsyncComponent from 'create-async-component'
 
const AsyncComponent = createAsyncComponent(
  () => import('./Home').then((mod) => mod.default),
  {
    loading: (homeProps) => <div>Loading...</div>,
    error: (exception, homeProps) => <div>Error!</div>,
  }
)
 
// Optionally preload the component
AsyncComponent.load()
 
// Use the component as you would any other component
<AsyncComponent foo='bar'/>

API

function createAsyncComponent<P>(
  componentGetter: AsyncComponentGetter<P>,
  options: AsyncComponentOptions<P> = {}
): AsyncComponent<P>
Argument Type Required? Description
componentGetter AsyncComponentGetter Yes A function that returns a React component or a promise that resolves a React component
options AsyncComponentOptions No Optionally adds loading and error state components. See AsyncComponentOptions

Returns AsyncComponent

Preload your component

// Simply call its load() method
AsyncComponent.load()
// Real world example
<Link onMouseEnter={AsyncComponent.load}/>

AsyncComponentGetter

export type AsyncComponentGetter<P> = () => AsyncComponentInterop<P>
export type AsyncComponentInterop<P> = 
  | Promise<React.ComponentType<P>>
  | React.ComponentType<P>

AsyncComponentOptions

export interface AsyncComponentOptions<P> {
  /**
   * This component will be renderered while the async component is loading
   */
  loading?: React.FC<P>
  /**
   * This component will be renderered when there is an error getting
   * the async component
   */
  error?: (exception: any, props: P) => ReturnType<React.FC<P>>
}

AsyncComponent

export interface AsyncComponent<P> extends React.FC<P> {
  /**
   * Starts preloading the asynchronous component
   */
  load: () => Promise<React.ComponentType<P>>
}

LICENSE

MIT

Package Sidebar

Install

npm i create-async-component

Weekly Downloads

9

Version

2.0.0

License

MIT

Unpacked Size

44.6 kB

Total Files

26

Last publish

Collaborators

  • jaredlunde