aboutsummaryrefslogtreecommitdiffstats
path: root/packages/website/ts/lazy_component.tsx
blob: 1dfe4db95f464c5e473fb8f42a2bf07fe9673739 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
import * as _ from 'lodash';
import * as React from 'react';

interface LazyComponentProps {
    reactComponentPromise: Promise<React.ComponentClass<any>>;
    reactComponentProps: any;
}

interface LazyComponentState {
    component?: React.ComponentClass<any>;
}

/**
 * This component is used for rendering components that are lazily loaded from other chunks.
 * Source: https://reacttraining.com/react-router/web/guides/code-splitting
 */
export class LazyComponent extends React.Component<LazyComponentProps, LazyComponentState> {
    constructor(props: LazyComponentProps) {
        super(props);
        this.state = {
            component: undefined,
        };
    }
    public componentWillMount() {
        // tslint:disable-next-line:no-floating-promises
        this.loadComponentFireAndForgetAsync(this.props);
    }
    public componentWillReceiveProps(nextProps: LazyComponentProps) {
        if (nextProps.reactComponentPromise !== this.props.reactComponentPromise) {
            // tslint:disable-next-line:no-floating-promises
            this.loadComponentFireAndForgetAsync(nextProps);
        }
    }
    public render() {
        return _.isUndefined(this.state.component) ?
                null :
                React.createElement(this.state.component, this.props.reactComponentProps);
    }
    private async loadComponentFireAndForgetAsync(props: LazyComponentProps) {
        const component = await props.reactComponentPromise;
        this.setState({
            component,
        });
    }
}

/**
 * [createLazyComponent description]
 * @param  componentName    name of exported component
 * @param  lazyImport       lambda returning module promise
 *                          we pass a lambda because we only want to require a module if it's used
 * @example `const LazyPortal = createLazyComponent('Portal', () => System.import<any>('ts/containers/portal'));``
 */
export const createLazyComponent = (componentName: string, lazyImport: () => Promise<any>) => {
    return (props: any) => {
        const reactComponentPromise = (async (): Promise<React.ComponentClass<any>> => {
            const mod = await lazyImport();
            const component = mod[componentName];
            return component;
        })();
        return (
            <LazyComponent
                reactComponentPromise={reactComponentPromise}
                reactComponentProps={props}
            />
        );
    };
};