Backbone.React.Component is a wrapper for React.Component and brings all the power of Facebook's React to Backbone.js.
Using Bower
bower install backbone-react-component
If you're not using Bower download the source from the dist folder.
Include the script on your webpage (or use RequireJS/Browserify)
...
<script type="text/javascript" src="path_to_script/backbone-react-component-min.js"></script>
...
It follows all the principles behind React.Component, though it binds models to the component's props and also automatically mounts the component into the component's $el.
/** @jsx React.DOM */
var MyComponent = Backbone.React.Component.extend({
render: function () {
return <div>{this.props.test}</div>;
}
});
var model = new Backbone.Model();
var newComponent = new MyComponent({
el: $('body'),
model: model
});
model.set('test', 'Hello world!');
The Component will listen to any model changes, making it automatically refresh using React's algorithm.
newComponent.mount();
var newComponent = new MyComponent({
el: $('body'),
collection: new Backbone.Collection([{helloWorld: 'Hello world!'}])
});
var MyComponent = Backbone.React.Component.extend({
createEntry: function (entry) {
return <div>{entry.helloWorld}</div>;
},
render: function () {
return <div>{this.props.collection.map(this.createEntry())}</div>;
}
});
var newComponent = new MyComponent({
el: $('body'),
model: {
firstModel: new Backbone.Model({helloWorld: 'Hello world!'}),
secondModel: new Backbone.Model({helloWorld: 'Hello world!'})
},
collection: {
firstCollection: new Backbone.Collection([{helloWorld: 'Hello world!'}]),
secondCollection: new Backbone.Collection([{helloWorld: 'Hello world!'}])
}
});
var MyComponent = Backbone.React.Component.extend({
createEntry: function (entry) {
return <div>{entry.helloWorld}</div>;
},
render: function () {
return (
<div>
{this.props.firstModel.helloWorld}
{this.props.secondModel.helloWorld}
{this.props.firstCollection.map(this.createEntry())}
{this.props.secondCollection.map(this.createEntry())}
</div>;
)
}
});
Besides inheriting all the methods from React.Component and Backbone.Events you can find the following methods:
props is a namespace and may contain el, model and collection properties. Model and collection properties may be multiple by passing a namespace.
Inspired by Backbone.View, it's a shortcut to this.$el.find method.
Gets the collection from the component's owner.
Gets the model from the component's owner.
Gets the component owner (greatest parent component).
- el (DOMElement)
- onRender (Callback) Mounts the component into the DOM and sets it has rendered (this.isRendered = true).
Unmounts the component. Throws an error if the component doesn't unmount successfully.
Stops component listeners, unmounts the component and then removes the DOM element.
- Improve models/collections requests error handling
- Improve the way how to detect bulk inserts (collection.add([])) to avoid extra calls to setPropsCollection
- Any ideas?