Last active
October 4, 2022 18:52
-
-
Save aantipov/2d288d3e33084c4348c85cf9da860db7 to your computer and use it in GitHub Desktop.
A simple way to convert React components into AngularJS components
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React from "react"; | |
import ReactDOM from "react-dom"; | |
import { fromPairs, map, pick } from "ramda"; | |
/** | |
* Wraps a React component into Angular component. Returns a new Angular component. | |
* | |
* Usage: angular.module('some.module').component('newAngularComponent', react2angular(MyReactComponent)) | |
* (the usage is the same as in similar lib https://github.com/coatue-oss/react2angular) | |
*/ | |
export default function react2angular(Class) { | |
const names = (Class.propTypes && Object.keys(Class.propTypes)) || []; | |
class Ctrl { | |
static get $inject() { | |
return ["$element", "$scope"]; | |
} | |
constructor($element, $scope) { | |
this.$element = $element; | |
this.$scope = $scope; | |
this.wrapFn = this.wrapFn.bind(this); | |
} | |
wrapFn(prop) { | |
if (typeof prop === "function") { | |
return (...args) => { | |
prop(...args); | |
this.$scope.$applyAsync(); | |
}; | |
} | |
return prop; | |
} | |
$onChanges() { | |
const props = pick(names, this); | |
// Wrap passed angular functions into $apply, because those functions | |
// are supposed to be invoked within React | |
// and we need to notify angular | |
const wrappedProps = map(this.wrapFn, props); | |
ReactDOM.render(<Class {...wrappedProps} />, this.$element[0]); | |
} | |
$onDestroy() { | |
ReactDOM.unmountComponentAtNode(this.$element[0]); | |
} | |
} | |
return { | |
bindings: fromPairs(names.map(name => [name, "<"])), | |
controller: Ctrl | |
}; | |
} |
Do you have an example usage, for example if you have a React component accepting X props, how do you include it in an Angular project with props and using this function?
Ah AngularJS not Angular..
Ah AngularJS not Angular..
😄
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Ramda can be easily replaced by Lodash