Skip to content

Instantly share code, notes, and snippets.

@aantipov
Last active October 4, 2022 18:52
Show Gist options
  • Save aantipov/2d288d3e33084c4348c85cf9da860db7 to your computer and use it in GitHub Desktop.
Save aantipov/2d288d3e33084c4348c85cf9da860db7 to your computer and use it in GitHub Desktop.

Revisions

  1. aantipov revised this gist May 5, 2017. 1 changed file with 2 additions and 2 deletions.
    4 changes: 2 additions & 2 deletions react2ng1.js
    Original file line number Diff line number Diff line change
    @@ -5,8 +5,8 @@ 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', reactToAngular(MyReactComponent))
    *
    * 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)) || [];
  2. aantipov renamed this gist May 5, 2017. 1 changed file with 0 additions and 0 deletions.
    File renamed without changes.
  3. aantipov created this gist May 5, 2017.
    55 changes: 55 additions & 0 deletions react2ng1
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,55 @@
    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', reactToAngular(MyReactComponent))
    *
    */
    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
    };
    }