2.0.0 • Published 4 years ago
create-async-component v2.0.0
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