Skip to content

Instantly share code, notes, and snippets.

@codeBelt
Last active June 16, 2022 17:57
Show Gist options
  • Save codeBelt/1fb48d4d52191c832692318c54626de1 to your computer and use it in GitHub Desktop.
Save codeBelt/1fb48d4d52191c832692318c54626de1 to your computer and use it in GitHub Desktop.
React Loadable TypeScript Examples
import * as Loadable from 'react-loadable';
import OptionsWithoutRender = LoadableExport.OptionsWithoutRender;
import AsyncLoader from '../components/AsyncLoader';
import {IProps} from './AddBeer';
const loadableOptions: OptionsWithoutRender<IProps> = {
loader: () => import(/* webpackChunkName: "AddBeer" */ './AddBeer'),
loading: AsyncLoader,
};
export default Loadable(loadableOptions);
import * as React from 'react';
import * as Loadable from 'react-loadable';
import OptionsWithRender = LoadableExport.OptionsWithRender;
import AsyncLoader from '../components/AsyncLoader';
import {IProps} from './AddBeer';
const loadableOptions: OptionsWithRender<IProps, any> = {
loader: () => import(/* webpackChunkName: "AddBeer" */ './AddBeer'),
loading: AsyncLoader,
render(loaded: any, props: IProps) {
const Component: any = loaded.default; // tslint:disable-line:variable-name
return <Component {...props} />;
},
};
export default Loadable(loadableOptions);
/*
<AddBeerAsync
data={'stuff'}
/>
*/
@iamamanbirdi
Copy link

Please share code of AsyncLoader

@codeBelt
Copy link
Author

For some reason I can add a new gist so here you go:

import * as React from 'react';

interface IProps {}
interface IState {}

export default class AsyncLoader extends React.Component<IProps & LoadableExport.LoadingComponentProps, IState> {
    public render(): JSX.Element {
        if (this.props.error) {
            return (
                <h3>
                    Could not load content. <button onClick={this.props.retry}>Retry</button>
                </h3>
            );
        } else if (this.props.timedOut) {
            return (
                <h2>
                    Taking longer than expected... <button onClick={this.props.retry}>Retry</button>
                </h2>
            );
        } else if (this.props.pastDelay) {
            return <h2>Loading...</h2>;
        } else {
            return null;
        }
    }
}

@katesroad
Copy link

Hi, Nice code. Can u share the LoadableExport code

@codeBelt
Copy link
Author

@katesroad it's been awhile since I wrote this code but looks like LoadableExport is part of the react-loadable library.
https://cdn.jsdelivr.net/npm/@types/[email protected]/index.d.ts

Check out the latest way to code split with the use of React lazy
https://github.com/codeBelt/react-redux-architecture/blob/TypeScript/src/views/App.tsx#L12

Also check out my article on the latest way I build react apps
https://medium.com/@robertsavian/my-awesome-react-redux-structure-6044e5007e22

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment