v2 React Props -> State Mixin
by Jon Beebe
HTML
<script src="http://fb.me/JSXTransformer-0.10.0.js"></script>
<script src="http://fb.me/react-with-addons-0.10.0.js"></script>
<script src="http://fb.me/react-js-fiddle-integration.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/moment.js/2.6.0/moment.min.js"/></script>
CSS
div {
padding: 1em;
}
.is-active {
background: #eee;
}
JavaScript 1.7
/** @jsx React.DOM */
var extend = _.extend;
// A simple class to capture a one-way value transform function.
var ValueTransformer = function (transform) {
this.func = (typeof transform === 'function')
? transform
: function (value) { return value; }
};
// Transforms the input value according to the pre-defined transform function
ValueTransformer.prototype.getTransformedValue = function (value) {
return this.func.call(null, value);
};
// Captures the ability to transform a property value into a state value
var ReactPropTransformer = function (propName, transform) {
this.propName = propName || null;
this.transformer = new ValueTransformer(transform);
};
// `propName` is optional since it can be overriden by the name pre-defined on the transformer.
// Typically you provide the same name as found on `this.props...` here.
// If the transform does not define a `this.propName` then the name provided here will be used.
ReactPropTransformer.prototype.getTransformedState = function (propName, propValue) {
var newState = {};
newState[this.propName || propName] = this.transformer.getTransformedValue(propValue);
return newState;
};
// Sets the state value on the given React component, running it through the
// pre-defined value transformer.
ReactPropTransformer.prototype.execute = function (component, propName, propValue) {
component.setState(this.getTransformedState(propName, propValue));
};
// Helps create a new React component prop-to-state transform type
var createReactPropTransformClass = function (transformName, transformFunc) {
var obj = {};
obj[transformName] = function (name) {
ReactPropTransformer.call(this, name, transformFunc);
};
obj[transformName].prototype = Object.create(ReactPropTransformer.prototype);
return obj[transformName];
};
// An example boolean transform, ensuring the transformed value is always a literal Boolean
var BooleanTransform =...