Skip to content

Instantly share code, notes, and snippets.

@mohsen1
Last active July 12, 2017 17:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mohsen1/5e0aacceb8368c9e5038334d8f1c82d0 to your computer and use it in GitHub Desktop.
Save mohsen1/5e0aacceb8368c9e5038334d8f1c82d0 to your computer and use it in GitHub Desktop.
import * as React from 'react';
import { RouteComponentProps } from 'react-router-dom';
interface LoadableProps<T> {
loader: (props: RouteComponentProps<T>) => (() => Promise<React.ComponentType<T>> | React.ComponentType<T>);
loading: React.ComponentType<T>;
}
export function Loadable<T>(loadableProps: LoadableProps<T>) {
return class LoadableComponent extends React.Component<RouteComponentProps<T>, { ResultComponent: React.ComponentType<T> }> {
state = { ResultComponent: null as any };
async componentWillMount() {
console.log('componentWillMount')
const loaderResult = loadableProps.loader(this.props);
if (typeof loaderResult === 'function') {
this.setState({ ResultComponent: await loaderResult() });
} else {
this.setState({ ResultComponent: loaderResult });
}
}
render() {
if (this.state.ResultComponent) {
return <this.state.ResultComponent />
}
return <loadableProps.loading />
}
}
}
import * as React from 'react';
import { LoadingComponentProps } from 'react-loadable';
/**
* Loading component. Renders a div with loading message
*/
export const Loading: React.StatelessComponent<LoadingComponentProps> = ({ isLoading, error, timedOut }) => {
if (timedOut) {
return (<div>Still loading...</div>);
}
if (error) {
const errorMessage = process.env.NODE_ENV === 'development' ? <pre>{String(error)}</pre> : null;
return (<div><p>Something went wrong...</p>{errorMessage}</div>)
}
return (<div>Loading...</div>);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment