Skip to content

Instantly share code, notes, and snippets.

@ryanflorence
Created May 13, 2015 23:57
Show Gist options
  • Save ryanflorence/35cb6be612aed04ef54f to your computer and use it in GitHub Desktop.
Save ryanflorence/35cb6be612aed04ef54f to your computer and use it in GitHub Desktop.
var React = require("react");
var { func } = React.PropTypes;
var assign = require("object-assign");
var ReactComponent = Ember.Component.extend({
reactProps: null,
reactActions: null,
setupReactPropsAndActions: function() {
var propTypes = this.get("reactComponentClass.propTypes");
var props = [];
var actions = {};
Object.keys(propTypes).forEach((name) => {
if (propTypes[name] === func || propTypes[name] === func.isRequired) {
actions[name] = function(...args) {
return this.sendAction.apply(this, [name].concat(args));
}.bind(this);
} else {
props.push(name);
this.addObserver(name, () => Ember.run.throttle(this, "reactRender", 10));
}
});
this.setProperties({
reactActions: actions,
reactProps: props,
});
}.on("init"),
reactRender() {
var props = this.getProperties(this.get("reactProps"));
var actions = this.get("reactActions");
var component = React.createElement(
this.get("reactComponentClass"),
assign({}, props, actions)
);
var el = this.get("element");
React.render(component, el);
},
didInsertElement () {
this.reactRender();
},
willDestroyElement () {
React.unmountComponentAtNode(this.get("element"));
}
});
ReactComponent.reopenClass({
from: function(component) {
return this.extend({
reactComponentClass: component,
});
},
});
module.exports = ReactComponent;
@ryanflorence
Copy link
Author

// react
var Something = React.createClass({})

// bridge to ember
App.ReactSomethingComponent = ReactComponent.from(Something)

// usage in ember
{{#react-something foo="bar" onStuff="someAction"}}

// - whenever `foo` changes it should cause a rerender in react
// - whenever react calls `onStuff` then `someAction` should be sent up

This lets you:

  • Write all new code in React, even inside of ember portions of the app
  • Migrate ember views one at a time, and when you hit a shared ember component across the whole app, instead of having an ember and a react version of the component, you can have only a react component
  • Then, when the other ember portions get rewritten in react, you already have the widely shared react components ready to go.

This is two years old for both react and ember, YMMV. I'm pretty sure the team had to tweak for edge cases but I don't have access to their code anymore.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment