Search code examples
javascriptcssreactjsdompolymer

React.Js and Polymer CSS


I have a react app I am trying to inject into a Polymer app. The Polymer app will handle the routing, etc, I just need the react app to appear on one of the pages fully styled/functional with event handlers etc. I cannot get the styles to apply properly.

<link rel="import" href="../bower_components/polymer/polymer-element.html">
<link rel="import" href="../bower_components/polymer/polymer.html">
<link rel="import" href="storm-styles.html">

<script src="../node_modules/react/dist/react.min.js"></script>
<script src="../node_modules/react-dom/dist/react-dom.min.js"></script>
<script type="text/javascript" src="../build/react-diagrams/static/js/main.aaa88ec6.js"></script>

<dom-module id="my-view4">
   <template>
     <style include="storm-styles"></style>
   </template>
   <script>
   class MyView4 extends Polymer.Element {
         static get is() { return 'my-view4'; }

         ready() {
           super.ready();
/*
           ReactDOM.render(
             React.createElement(
               Provider,
               null,
               React.createElement(
                 App,
                 null
               )
             ),
             this.shadowRoot
           );*/
         }
    }

    window.customElements.define(MyView4.is, MyView4);
   </script>
</dom-module>

if I uncomment the ReactDOM.render() function then the <style> element vanishes and the React app doesn't work, but it appears in the DOM.


Solution

  • Problem is that ReactDOM.render() updates the DOM by erasing all nodes and re-writing them. So since I'm writing to this.shadowRoot, the styles get over-written.

    This can be solved by adding a container div as follows:

    <dom-module id="my-view4">
       <template>
         <style include="storm-styles"></style>
         <div id="reactcontainer"></div>
       </template>
       <script>
       class MyView4 extends Polymer.Element {
             static get is() { return 'my-view4'; }
    
             ready() {
               super.ready();
    
               ReactDOM.render(
                 React.createElement(
                   Provider,
                   null,
                   React.createElement(
                     App,
                     null
                   )
                 ),
                 this.$.reactcontainer
               );
             }
        }
    
        window.customElements.define(MyView4.is, MyView4);
       </script>
    </dom-module>