UNPKG

react18-react2angular

Version:

The easiest way to embed React components in Angular 1 apps! react 18 compatible

59 lines 2.17 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.react2angular = void 0; const lodash_1 = require("lodash"); const ngcomponent_1 = require("ngcomponent"); const React = require("react"); const client_1 = require("react-dom/client"); /** * 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']) * ``` */ function react2angular(Class, bindingNames = null, injectNames = []) { const names = bindingNames || (Class.propTypes && Object.keys(Class.propTypes)) || []; return { bindings: lodash_1.fromPairs(names.map(_ => [_, '<'])), controller: ['$element', ...injectNames, class extends ngcomponent_1.default { constructor($element, ...injectedProps) { super(); this.$element = $element; this.isDestroyed = false; this.injectedProps = {}; injectNames.forEach((name, i) => { this.injectedProps[name] = injectedProps[i]; }); this.root = client_1.createRoot($element[0]); } static get $$ngIsClass() { return true; } $onInit() { names.forEach((name) => { this.props[name] = this[name]; }); } render() { if (!this.isDestroyed) { this.root.render(React.createElement(Class, Object.assign({}, this.props, this.injectedProps))); } } componentWillUnmount() { this.isDestroyed = true; if (this.$element[0] && this.root) { this.root.unmount(); } } }] }; } exports.react2angular = react2angular; //# sourceMappingURL=index.js.map