Or, to spare people from having to suffer through yet another video tutorial (sorry, but I really don’t like them):
- Install the npm-module
react-loadable - Create a React component named
Loading.tsxwhich is displayed while the component loads
import React from 'react';
export default function Loading({ isLoading, pastDelay, error }) {
if (isLoading && pastDelay) {
return <p>Loading...</p>;
} else if (error && !isLoading) {
return <p>Error!</p>;
} else {
return null;
}
}
_3. Create a wrapper function in a file named MyLoadable.js
import Loadable from 'react-loadable';
import Loading from './Loading';
export default function MyLoadable(opts) {
return Loadable({
LoadingComponent: Loading,
delay: 200,
...opts
});
}
and then import your components you want to load later like this:
import MyLoadable from './MyLoadable';
const MyDeferredComponent = MyLoadable({
loader: () => import('./MyDeferredComponent')
});
Please also note that VSCode will mark the latter code as an error and TypeScript most likely won’t like it at all.