Skip to content

Instantly share code, notes, and snippets.

@aantipov
Last active October 4, 2022 18:52
Show Gist options
  • Star 11 You must be signed in to star a gist
  • Fork 5 You must be signed in to fork a gist
  • Save aantipov/2d288d3e33084c4348c85cf9da860db7 to your computer and use it in GitHub Desktop.
Save aantipov/2d288d3e33084c4348c85cf9da860db7 to your computer and use it in GitHub Desktop.
A simple way to convert React components into AngularJS components
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
};
}
@aantipov
Copy link
Author

aantipov commented May 5, 2017

Ramda can be easily replaced by Lodash

@OZZlE
Copy link

OZZlE commented Feb 22, 2022

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?

@OZZlE
Copy link

OZZlE commented Feb 22, 2022

Ah AngularJS not Angular..

@aantipov
Copy link
Author

Ah AngularJS not Angular..

😄

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment