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
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>
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
|
A react-router-dom/Link
component with a preload
prop
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. |
A react-router-dom/NavLink
component with a preload
prop. See <Link>
.
type AsyncRouteType<P> = React.FC<AsyncRouteProps> & {
load: AsyncComponentGetter<P>
}
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>
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[]
}
MIT