const loadable = (loaderFunction) => class AsyncComponent extends React.Component { state = { ResultComponent: null, error: false, }; componentWillMount() { loaderFunction .then(result => this.setState({ ResultComponent: result.default || result})) // "es6" default export .catch(() => this.setState({ error: true }); } render() { const { error, ResultComponent } = this.state; // Display loaded component return ResultComponent ? <ResultComponent {...this.props}/> : (error ? <ErrorComponent /> : <LoadingComponent />) } }
At the same time there is a solution, and again in 4 lines - renderProps
const loadableModule = (loaderFunction) => class AsyncComponent extends React.Component { state = { ResultComponent: null, error: false, }; componentWillMount() { loaderFunction .then(result => this.setState({ module: result.default || result})) // "es6" default export .catch(() => this.setState({ error: true }); } render() { const { error, module } = this.state; return module // pass it as a render prop! ? this.props.children(module) // pass it as a render prop! : (error ? <ErrorComponent /> : <LoadingComponent />) } }
import loadable from '@loadable/component' const Moment = loadable.lib(() => import('moment')) function FromNow({ date }) { return ( <div> <Moment fallback={date.toLocaleDateString()}> {({ default: moment }) => moment(date).fromNow()} </Moment> </div> ) }
import {importedLibraryDefault} from 'react-loadable-library'; const Moment = importedLibraryDefault( () => import('momentjs')); <Moment> { (momentjs) => <span> {momentjs(date).format(FORMAT)}</span> } </Moment>
// react-loadable-library, Suspense
And who will rewrite it on hooks?
Source: https://habr.com/ru/post/443124/
All Articles