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>
CSS
div {
padding: 1em;
}
.is-active {
background: #eee;
}
JavaScript 1.7
/** @jsx React.DOM */
// 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;
ValueTransformer.call(this, transform);
};
ReactPropTransformer.prototype = Object.create(ValueTransformer.prototype);
// Sets the state value on the given React component, running it through the
// pre-defined value transformer. Optionally transform the name of the property
// with the second parameter if it does not match the prop name.
ReactPropTransformer.prototype.execute = function (component, propName, propValue) {
var newState = {};
newState[this.propName || propName] = this.getTransformedValue(propValue);
component.setState(newState);
};
// 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 = createReactPropTransformClass('BooleanTransform', function (value) {
return !!value;
});
var PropsToStateMixin = {
componentWillReceiveProps: function(nextProps) {
var props = this.propsForState();
for(var key in props) {
if(props.hasOwnProperty(key)...