Search code examples
reactjsreact-component

How to create a redistributable widget using React


I want to build a widget using React that can be consumed by non-spa sites by pointing to a js file and adding a javascript snippet. E.g.

<script src="somepath/mycomponent.min.js"></script>
<script>MyComponent.render('id-of-a-div')</script>

I have created a component with React and setup webpack. I most spa-cases the top-level component ends with

ReactDOM.render(<MyComponent/>, document.getElementById(id));

My component won't be able to do this since it doesn't know to which element to render itself.

How and where should I create the function that would attach the component to an element?


Solution

  • you need a file with the methods that initialize and interacts with the parent page.

    Maybe in utilities.js

     export const utilities = {
       // Here you will initialize the widget and you could pass an argument 
      // with the id of the tag where you wanna inject the app 
    
       initWidget: ( elementId ) => {
        if( !elementId ){
         document.createElement( 'rootApp' ); 
         ReactDOM.render(<MyComponent/>, document.getElementById('rootApp'));
        }
        else {
         ReactDOM.render(<MyComponent/>, document.getElementById(id));
         }
       },
     } 
    

    And the utility will work in the tag of html to initilize it right there after all the js is loaded:

    <script type='text/javascript' src='/widget.js'></script>
    <script>
     utilities.initWidget( 'myCustomId' );
    </script>
    

    Maybe a flow like this could be useful to you.