Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Code example for a component that loads another react component from external servers
import {Component} from "react";
var CrossCustomEvent = require('customevent');
var scriptLoader = require("load-script");
module.exports = function(identifier) {
/* Customers pass some kind of identifier to this function.
* It might be a user name or an access key.
* Something that identifies the location of the script code of this customer
*/
class Wrapper extends Component {
componentDidMount = () => {
var propsToPass = Object.assign({}, this.props);
/*
* The loaded component code is accessible by a unique global variable
* As soon as that code is loaded this component will call it
* and pass its DOM element and the props to it
*/
if (window.MyWidgetRenderer) {
window.MyWidgetRenderer(this.$container, propsToPass);
} else {
scriptLoader(`path of customer specific script, might be derived from ${identifier}`, () => {
this.forceUpdate(() => {
window.MyWidgetRenderer && window.MyWidgetRenderer(this.$container, propsToPass);
});
});
}
}
componentWillUnmount = () => {
/*
* Problem is that the widget will not automatically detach if this wrapper is unmounted
* I solved the problem by common event on which the widget listens and cleans itself up
*/
document.dispatchEvent(new CrossCustomEvent('widget.unmounted'));
}
setRef = (node) => { this.$container = node; }
render: () => {
var props = this.props;
return <div {...props.nodeAttrs} ref={this.setRef}>
{
(window && window.MyWidgetRenderer) ? null : props.children
}
</div>;
}
};
Wrapper.defaultProps = {
nodeAttrs: []
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment