Skip to content

Instantly share code, notes, and snippets.

@kmck
Last active October 3, 2016 19:57
Show Gist options
  • Save kmck/306c212e356b3f5a4563d58cb23805ef to your computer and use it in GitHub Desktop.
Save kmck/306c212e356b3f5a4563d58cb23805ef to your computer and use it in GitHub Desktop.
Backbone.View wrapper for a React component
var ReactComponentView = Backbone.View.extend({
initialize: function(options) {
if (options) {
this.setComponent(options.ComponentClass, options.componentProps, options.componentChildren);
}
},
setComponent: function(ComponentClass, componentProps, componentChildren) {
(typeof ComponentClass === 'undefined') || (this.ComponentClass = ComponentClass);
(typeof componentProps === 'undefined') || (this.componentProps = componentProps);
(typeof componentChildren === 'undefined') || (this.componentChildren = componentChildren);
},
component: function() {
var ComponentClass = this.ComponentClass;
if (!ComponentClass) {
throw new Error('ReactComponentView requires a ComponentClass!');
}
var props = this.componentProps;
if (typeof props === 'function') {
props = props();
}
var children = this.componentChildren;
if (typeof children === 'function') {
children = children();
}
return React.createElement(ComponentClass, props, children);
},
render: function() {
ReactDOM.render(this.component(), this.el);
return this;
},
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment