Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to create an embedded react app widget?

I want to create a widget that can be embedded onto different WordPress sites. As an example building a mortgage calculator and adding functionality such as creating a downloadable PDF with the inputted information.

Is it possible to do this with react? More specifically using the create-react-app tool.

Thank you in advance!

like image 408
Michael Carniato Avatar asked Oct 11 '18 01:10

Michael Carniato


People also ask

Can we embed React app?

Easy to Embed React AnywhereA simple script tag is all that's required to use one of our embedded React apps, which makes them easy to add to any page or framework.


1 Answers

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>
like image 54
Kiruahxh Avatar answered Sep 24 '22 06:09

Kiruahxh