47 lines
1.4 KiB
TypeScript
47 lines
1.4 KiB
TypeScript
import { IAugmentedJQuery, IComponentOptions } from 'angular'
|
|
import fromPairs = require('lodash.frompairs')
|
|
import NgComponent from 'ngcomponent'
|
|
import * as React from 'react'
|
|
import { render, unmountComponentAtNode } from 'react-dom'
|
|
|
|
/**
|
|
* Wraps a React component in Angular. Returns a new Angular component.
|
|
*
|
|
* Usage:
|
|
*
|
|
* ```ts
|
|
* type Props = { foo: number }
|
|
* class ReactComponent extends React.Component<Props, S> {}
|
|
* const AngularComponent = react2angular(ReactComponent, ['foo'])
|
|
* ```
|
|
*/
|
|
export function react2angular<Props>(
|
|
Class: React.ComponentClass<Props> | React.SFC<Props>,
|
|
bindingNames: (keyof Props)[] | null = null,
|
|
injectNames: string[] = []
|
|
): IComponentOptions {
|
|
const names = bindingNames
|
|
|| (Class.propTypes && Object.keys(Class.propTypes))
|
|
|| []
|
|
|
|
return {
|
|
bindings: fromPairs(names.map(_ => [_, '<'])),
|
|
controller: ['$element', ...injectNames, class extends NgComponent<Props> {
|
|
injectedProps: { [name: string]: any }
|
|
constructor(private $element: IAugmentedJQuery, ...injectedProps: any[]) {
|
|
super()
|
|
this.injectedProps = {}
|
|
injectNames.forEach((name, i) => {
|
|
this.injectedProps[name] = injectedProps[i]
|
|
})
|
|
}
|
|
render() {
|
|
render(<Class {...this.injectedProps} {...this.props} />, this.$element[0])
|
|
}
|
|
componentWillUnmount() {
|
|
unmountComponentAtNode(this.$element[0])
|
|
}
|
|
}]
|
|
}
|
|
}
|