Last active
December 2, 2017 20:36
-
-
Save BjoernRuberg/53de538963aec7bed820432e5046b6d2 to your computer and use it in GitHub Desktop.
Code example for a component that loads another react component from external servers
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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