1.1.3 • Published 4 years ago

create-async-route v1.1.3

Weekly downloads
3
License
MIT
Repository
github
Last release
4 years ago

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

ArgumentTypeRequired?Description
componentGetterAsyncComponentGetterYesA function that returns a Promise e.g. an import() function
optionsAsyncComponentOptionsNoSee 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

PropTypeRequired?Description
preloadAsyncRouteType<any>falseProviding 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