create-async-route

A factory function for creating asynchronous react-router routes and a <Link> component with a preload prop for preloading those routes onMouseEnter.

Usage no npm install needed!

<script type="module">
  import createAsyncRoute from 'https://cdn.skypack.dev/create-async-route';
</script>

README


create-async-route

Bundlephobia Types Code coverage Build status NPM Version MIT License

npm i create-async-route

A factory function for creating asynchronous react-router routes and a component with a preload prop for preloading those routes onMouseEnter

Quick Start

import {createAsyncRoute} from 'create-async-route'

const HomeRoute = createAsyncRoute(() => import('./Home'))

<Router>
  // Use your route
  <HomeRoute path='/'/>
</Router>

// Preload your route generally speaking
HomeRoute.load()

// Preload your route `onMouseEnter` or `onTouchStart` with a <Link>
import {Link} from 'create-async-route'

<Link to='/' preload={HomeRoute}>
  Go home
</Link>

API

function createAsyncRoute<P>(
  component: AsyncComponentGetter<P>,
  options?: AsyncComponentOptions<P>
): AsyncRouteType<P>

Returns a <Route> from react-router-dom with a load method for preloading your async component. See AsyncRouteType

Argument Type Required? Description
componentGetter AsyncComponentGetter Yes A function that returns a Promise e.g. an import() function
options AsyncComponentOptions No See AsyncComponentOptions

<Link>

A react-router-dom/Link component with a preload prop

Props

This component provides all of the props found in react-router-dom/Link in addition to the ones below

Prop Type Required? Description
preload AsyncRouteType<any> false Providing an async route component here will preload that component when onMouseEnter or onTouchStart is fired on the link.

<NavLink>

A react-router-dom/NavLink component with a preload prop. See <Link>.

Types

AsyncRouteType

type AsyncRouteType<P> = React.FC<AsyncRouteProps> & {
  load: AsyncComponentGetter<P>
}

AsyncComponentGetter

type AsyncComponentGetter<P> = () => ModuleComponentInterop<P>

type ModuleComponent<P = any> = {
  [property: string]: React.FunctionComponent<P> | React.ClassType<P, any, any>
}

type ModuleComponentInterop<P> =
  | Promise<ModuleComponent<P>>
  | ModuleComponent<P>

AsyncComponentOptions

interface AsyncComponentOptions<P> {
  // The property within the module object where
  // your component resides.
  // Default: "default"
  property?: string
  // A component you'd like to display while the async
  // component is loading.
  loading?: (props: P) => React.ReactNode | React.ReactNode[]
  // A component you'd like to display when the async
  // component is Promise is rejected.
  error?: (exception: any, props: P) => React.ReactNode | React.ReactNode[]
}

LICENSE

MIT