Skip to content

Instantly share code, notes, and snippets.

@mbruno-kr
Created February 1, 2022 21:22
Show Gist options
  • Save mbruno-kr/148fe327c8fab63eaf986a0abdd69c35 to your computer and use it in GitHub Desktop.
Save mbruno-kr/148fe327c8fab63eaf986a0abdd69c35 to your computer and use it in GitHub Desktop.

Required Modules

  • lodash
  • react

Usage

Basic Usage

<LazyComponent<PropsOfElement>
 component={()=> import('./Element')}
 any="props"
 the="element"
 needs
/>

With Child Component

<LazyComponent<PropsOfElement>
 component={()=> import('./Element')}
 any="props"
 the="element"
 needs
>
  <SimpleElement />
</LazyComponent> 
/* eslint-disable @typescript-eslint/no-explicit-any */
import { pickBy } from 'lodash';
import React, { Suspense } from 'react';
/**
*
* @example Dynamically Load Component
* <LazyComponent<PropsOfElement>
* component={()=> import('./Element')}
* any="props"
* the="element"
* needs
* />
* @example Dynamically load with children
* <LazyComponent<PropsOfElement>
* component={()=> import('./Element')}
* any="props"
* the="element"
* needs
* >
* <SimpleElement />
* </LazyComponent>
*
*/
export default function LazyComponent<T>(
props: T & { component: () => Promise<{ default: React.ComponentType<any> }> }
): JSX.Element {
const Component = React.lazy(props.component);
const Props = pickBy(props, (_value, key) => key !== 'component');
return (
<div>
<Suspense fallback={<div>Loading...</div>}>
<Component {...Props} />
</Suspense>
</div>
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment