Is it possible to create an embedded react app widget?
It is possible to create react embeddable widgets, but create-react-app
is not the right tool to do that.
The easiest way to share a compiled js bundle and to use it in a browser is to package it in the UMD format.However, create-react-app
doesn't support it. Technically, you can import a bundle from create-react-app as a widget, but it is a pain. Some people do this by parsing the application manifest, and other by copying the index html content into the destination page. Most of the time, a widget takes input data and you'll have hard time with these techniques.
I'd suggest you to use another build system that supports UMD out of the box, like parcel/babel (easiest one), webpack/babel, nwb, etc.Here are react official recommendations about compile chains.
Here is an example index.js
file you could use to declare a widget :
import React from 'react';import ReactDOM from 'react-dom';import './index.css';import App from './App';window.MyWidget = function(idElement, param1, param2) { let config = {param1, param2}; ReactDOM.render(<App config={config} />, document.getElementById(idElement)); return this;}
The widget can then be instantiated into the target page :
<body> <div id="react-widget"> <script src="http://cdm.com/my-react-widget-bundle.js"></script> <!-- if bundled separately, load the css --> <script> window.addEventListener("DOMContentLoaded", function(event) { new MyWidget("#react-widget", "toto", "tata"); }); </script> </div></body>
The second argument of ReactDOM.render is the render target. It can be anywhere on the page.
ReactDOM.render(element, document.getElementById('widgetTarget'));