Skip to content

Instantly share code, notes, and snippets.

@sloria
Last active April 8, 2018 02:00
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save sloria/767c170f92cb9118c591 to your computer and use it in GitHub Desktop.
Save sloria/767c170f92cb9118c591 to your computer and use it in GitHub Desktop.
mithril-like modules in react
/** Sugar for creating a React component from a mithril-like module. */
var defcomponent = function(module) {
var component = {
componentWillMount() {
if (module.hasOwnProperty('controller')) {
this.ctrl = new module.controller(this.props, this.props.children);
}
},
render() {
return module.view.call(this, this.ctrl, this.props, this.props.children);
}
};
// Merge all properties of module into the react component
$.extend(component, module);
return React.createClass(component);
};
var d = React.DOM;
// DEFINING COMPONENTS
var Panel = {};
// Use ES6 destructuring to define initial state in controller
Panel.controller = function({enabled=true}={}) {
this.enabled = enabled;
}
// Similarly define default props
Panel.view = function(ctrl, {header='Default header'}={}, children}) {
return d.div({className: 'panel panel-default', display: ctrl.enabled ? 'display' : 'none'},
d.div({className: 'panel-header', header}, children);
);
}
Panel = defcomponent(Panel);
var EditPanel = {};
EditPanel.view = function(ctrl, props, children) {
return Panel({header: 'Edit'}, 'Content Here')
}
// We can still use React's lifecycle hooks!
EditPanel.componentWillMount = function() {console.log('mounting!');};
EditPanel.shouldComponentUpdate = function(nextProps, nextState) { console.log('optimize!') };
EditPanel = defcomponent(EditPanel);
// We can (optionally) use jsx
Panel.view = function(ctrl, {header='Default header'={}, children}) {
return (
<div className="panel panel-default" style={{display: ctrl.enabled ? 'display' : 'none'}}>
<div class="panel-header">{header}</div>
{children}
</div>
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment