Last active
January 18, 2022 18:51
-
-
Save nekitk/1241942f23824b031b5d26190bd50359 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React from 'react' | |
export const getLazyComponent = (componentImport) => { | |
const LazyComponent = React.lazy(componentImport) | |
return () => ( | |
<LazyComponentErrorBoundary> | |
<React.Suspense fallback={'Loading...'}> | |
<LazyComponent /> | |
</React.Suspense> | |
</LazyComponentErrorBoundary> | |
) | |
} | |
class LazyComponentErrorBoundary extends React.Component { | |
state = { | |
error: false, | |
} | |
static getDerivedStateFromError() { | |
return { error: true } | |
} | |
render() { | |
return this.state.error | |
? 'Failed to load component, please refresh the page to try again' | |
: this.props.children | |
} | |
} | |
// Usage with default export | |
const LazyDefaultComponent = getLazyComponent(() => import('./MyComponent')) | |
// Usage with named export | |
// See https://github.com/reactjs/rfcs/blob/gaearon-patch-2/text/0000-lazy.md#why-the-default-field | |
const LazyNamedComponent = getLazyComponent(() => | |
import('./MyComponent').then((res) => ({ default: res.MyComponent })) | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment