Package detail

create-async-component

jaredLunde12MIT2.0.0

A factory function for creating asynchronous React components

react, react component, create async component, async react component

readme


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

```jsx harmony import * as React from 'react' import createAsyncComponent from 'create-async-component'

const AsyncComponent = createAsyncComponent( () => import('./Home').then((mod) => mod.default), { loading: (homeProps) =>

Loading...
, error: (exception, homeProps) =>
Error!
, } )

// Optionally preload the component AsyncComponent.load()

// Use the component as you would any other component

<AsyncComponent foo='bar'/>


## API

```typescript
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

changelog

Changelog

All notable changes to this project will be documented in this file. See standard-version for commit guidelines.

2.0.0 (2020-07-06)