Created
May 27, 2015 10:07
-
-
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.
This file contains hidden or 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
// 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