Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@cjohansen
Created May 27, 2015 10:07
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cjohansen/8f9001749dba5b9b306f to your computer and use it in GitHub Desktop.
Save cjohansen/8f9001749dba5b9b306f to your computer and use it in GitHub Desktop.
createComponent is 18 lines of JavaScript that puts a lean and enjoyable interface on top of React's somewhat clunky and non-JSX-hostile API.
// Most components are defined fully by their render function,
// and all they need to access is the props
var myComponent = createComponent(function (props) {
return React.DOM.h1({}, "Hello " + props.name);
});
// ...which can be done very succinctly with ES6:
const {h1, div} = React.DOM;
const myComponent = createComponent(({name}) => h1({}, `Hello ${name}`));
// You can also define the full object if you need to implement other hooks:
var myOtherComponent = createComponent({
shouldComponentUpdate(newProps) {
return newProps.data !== this.props.data;
},
render({name}) {
return h1({}, `Hello again, ${name}`);
}
});
// Use:
var appData = {name: "Some Programmer"};
React.render(
div({}, myComponent(appData), myOtherComponent(appData)),
document.getElementById("app")
);
// All you need is this little helper (ES5, could be simplified with ES6)
function createComponent(render) {
var def = typeof render === 'function' ? {render: render} : render;
render = def.render;
def.render = function () {
return render.call(this, this.props.data, this.props.children);
};
if (!def.getInitialState) {
def.getInitialState = function () { return {}; };
}
var component = React.createFactory(React.createClass(def));
return function (data) {
return component.apply(this, [{data: data}].concat([].slice.call(arguments, 1)));
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment