Michael Carniato
Michael Carniato

Reputation: 83

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!

Upvotes: 8

Views: 7208

Answers (2)

Kiruahxh
Kiruahxh

Reputation: 2075

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>

Upvotes: 10

dhudson
dhudson

Reputation: 571

The second argument of ReactDOM.render is the render target. It can be anywhere on the page.

ReactDOM.render(element, document.getElementById('widgetTarget'));

Upvotes: 1

Related Questions