1

I am working on a fairly complex web app using React.js, and I would like to allow the app's users to use one of the components as an API widget on their sites as well with a script tag (think Google Maps API, Analytics, etc.)

I'm new to React, but I think React takes all of the components, etc. in the app, and bundles them into a single JS file.

Is it possible to bundle only one component into a JS file, then let users place that file in their site, and use it as a widget?

I've tried transpiling the component I want users to use as a widget with reactify, but I can't seem to get it to work.

Any thoughts?

tsteve
  • 549
  • 1
  • 7
  • 16

1 Answers1

1

Absolutely, however they will still need to include React as a dependency, or you would have to in your widget.

To use React you don't need to use transpilation, i.e. you don't need reactify. Building a widget for React is like building a widget for jQuery.

// Your widget root component
var SayHelloComponent = React.createClass({
  render() {
    // You use React.createElement API instead of JSX
    return React.createElement('span', null, "Hello " + this.props.name + "!");
  }
});


// This is a function so that it can be evaluated after document load
var getWidgetNodes = function () { 
  return document.querySelectorAll('[data-say-hello]'); 
};

function initializeWidget(node) {
  // get the widget properties from the node attributes
  var name = node.getAttribute('data-say-hello');

  // create an instance of the widget using the node attributes 
  // as properties
  var element = React.createElement(SayHelloComponent, { name: name });
  ReactDOM.render(element, node);
}

getWidgetNodes().forEach(initializeWidget);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

<!-- What it would look to include your widget in a page -->
<div data-say-hello="Guzart"></div>

The only reason you would need to transpile your code would be to use JSX and ES6.

guzart
  • 3,700
  • 28
  • 23
  • My component uses both JSX and ES6. Haha. So, you think transpiling a component that uses JSX and ES6 will work as a widget? Could I put React directly in the widget so the user doesn't have to add another js dependency on his or her site? – tsteve Nov 07 '16 at 16:37
  • Transpiling from ES6 and JSX will output something similar to the code snippet in the answer. And yes you could include React and ReactDOM with your widget, better yet is to load them async if they are not already included in the page. The important point here is that you understand what are the minimum pieces to get a react widget working. In your question you mention that you can't seem to get it to work, without the code and configuration is very hard to help you identify the problems. – guzart Nov 07 '16 at 16:45