Skip to content

Instantly share code, notes, and snippets.

@ThisIsMissEm
Last active December 4, 2020 14:14
Show Gist options
  • Save ThisIsMissEm/4daa6dfe1f5acb2085fb6e649f056b3c to your computer and use it in GitHub Desktop.
Save ThisIsMissEm/4daa6dfe1f5acb2085fb6e649f056b3c to your computer and use it in GitHub Desktop.
How to use loadable component properly with react-router using full dynamic imports and correct typescript types.
import loadable, { LoadableComponent } from '@loadable/component';
import { RouteComponentProps } from 'react-router-dom';
import { StaticContext } from 'react-router';
import { LocationState } from 'history';
// Autogenerated Types for the Capabilities and their Screens:
import { Capabilities, Screens } from './routeTypes';
export * from 'react-router-dom';
export function createScreen<
Params extends { [K in keyof Params]?: string } = Record<string, string>,
Context extends StaticContext = StaticContext,
State = LocationState,
// Note: when we currently pass any of the above as generics,
// we loose per-screen typing; I've no idea how to work around this:
Capability extends Capabilities = keyof Screens
>(
capability: Capability,
screen: Screens[Capability],
): LoadableComponent<RouteComponentProps<Params, Context, State>> {
return loadable<RouteComponentProps<Params, Context, State>>(
() => import(`../capabilities/${capability}/screens/${screen}`),
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment