简体   繁体   中英

How to use react custom package into an angular directive

Hi i have an angular v1.x application and a react custom package.


I want to be able to use the react custom package into the angular directive, which eventually will display a react component.

some code:


  1. angular app:

directive that consumes the my-package

import app from '../../main'
import React from "react";
import ReactDOM from "react-dom";
import Mypackage from 'my-package';

const reactDirective = app.directive('injectReact', function() {
 return {
  template: '<div id="reactapp" class="react-part"></div>',
  scope: {},
  link: function(scope, el, attrs){
        scope.newItem = (value) => {alert (value)}

        const reactapp = document.getElementById('reactapp')
        scope.$watch('scopeval', function(newValue, oldValue) {
            if (angular.isDefined(newValue)) {
             ReactDOM.render(
                 <div>
                    <Mypackage />
                 </div>
                , reactapp);
           }
        }, true);
     }
  }
})
  1. The package is linked into the project, so 'my-package' is inside angular's node_modules folder.

  2. The application uses bower & gruntfile.js to gother all the js files of the application

  3. i cant use import or require into the directive file.

  4. so i miss some babel / browserify configuration to make this work.????

Any help is welcome.

The easiest way you can achieve this is by using external package like react2angular . This package allows you to create angular.js wrapper components which will render specific react components, allowing you to pass props to them. Linking process is quite simple:

angular
  .module('myModule', [])
  .component('myComponent', react2angular(MyComponent, [], ['$http', 'FOO']))

If you want to create you own wrapping library checkout how it's made here (rendering, passing props and watching for changes to them)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM