Search code examples
angularreactjsangular6custom-elementangular-elements

How to add react custom element in angular 6


I have created a react application and defined it as custom element. customElements.define('react-iis', ReactElement); i have built this application and got js files i use this element directly inside normal html file it works fine but how can i call this element from angular component/html?

in Basic html, i imported react js files i got after build and used the <react-iis></react-iis> it works

<html>
<body>
<react-iis></react-iis>
<script type="text/javascript" src="../../reactelementsbuild/build/static/js/2.8490447d.chunk.js"></script>
  <script type="text/javascript" src="../../reactelementsbuild/build/static/js/main.1cd38f24.chunk.js"></script>
  <script type="text/javascript" src="../../reactelementsbuild/build/static/js/runtime~main.a8a9905a.js"></script>
</body>
<html>

Can anyone help to do the same from angular component


Solution

  • In Angular you will have to import your .js files in angular.json. (You might even merge those files into one, and then you only have to import one instead of three)

    "scripts": [
      "src/assets/react-component/2.8490447d.chunk.js",
      "src/assets/react-component/main.1cd38f24.chunk.js",
      "src/assets/react-component/runtime~main.a8a9905a.js"
    ]
    

    After that you will have to let Angular know that you will be using non angular elements / elements unknown to your application - CUSTOM_ELEMENTS_SCHEMA

    app.module.ts

    @NgModule({
      ....
      schemas: [CUSTOM_ELEMENTS_SCHEMA]
    })
    export class AppModule {
    }
    

    Now you are ready to use your react custom element same way as you used it in your React app - by using <react-iis></react-iis>