Skip to content

Instantly share code, notes, and snippets.

@omichelsen
Last active January 28, 2020 21:31
Show Gist options
  • Save omichelsen/45bd9c6888d38af300567ea3244b7d49 to your computer and use it in GitHub Desktop.
Save omichelsen/45bd9c6888d38af300567ea3244b7d49 to your computer and use it in GitHub Desktop.
ReactLoader
import { OnDestroy, OnInit } from '@angular/core'
export type VoidFunction = () => void
export interface ReactAppInit {
default(component: Element, ...args: any[]): VoidFunction
}
export default class ReactLoaderComponent<T extends {}> implements OnInit, OnDestroy {
constructor(
// A promise fetching the React component bundle
private readonly modulePromise: Promise<ReactAppInit>,
// Angular component DOM element to render React in
private readonly domElement: Element,
// Props that will be passed directly to the React component
private readonly reactProps: T,
) {}
private unmountReact: VoidFunction = () => undefined
ngOnInit() {
// Fetch the React component bundle and get the default export
this.modulePromise.then(({ default: init }) => {
// Render the React component in the DOM element and pass on the props
// keeping a reference to the unmount function returned by `init`
this.unmountReact = init(this.domElement, this.reactProps)
})
}
ngOnDestroy() {
// Unmount the React component when the Angular component unmounts
this.unmountReact()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment