Skip to content

Instantly share code, notes, and snippets.

@parshap
Created March 26, 2014 17:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save parshap/9789332 to your computer and use it in GitHub Desktop.
Save parshap/9789332 to your computer and use it in GitHub Desktop.
"use strict";
// A function that wraps a given `React.DOM.input`-like component to
// apply formatting to the value for display purposes.
//
// Example:
//
// var RoundedInput = createFormattedInput(React.DOM.input, {
// set: Math.round,
// });
var React = require("react");
var isFunction = require("core-util-is").isFunction;
var defaults = require("underscore").defaults;
var filter = require("object-filter");
var getOnChange = require("react/lib/LinkedValueUtils").getOnChange;
function getValue(props) {
return props.valueLink ? props.valueLink.value : props.value;
}
function filterKeys(obj, keys) {
return filter(obj, function(val, key) {
return keys.indexOf(key) === -1;
});
}
module.exports = function(Component, options) {
return React.createClass({
getState: function(props) {
var value = String(getValue(props));
return {
value: format.call(this, value),
};
},
getInitialState: function() {
return this.getState(this.props);
},
componentWillReceiveProps: function(props) {
this.setState(this.getState(props));
},
handleChange: function(e) {
this.setState({ value: e.target.value });
},
handleFormat: function() {
var value = unformat.call(this, this.state.value);
var e = { target: { value: value } };
getOnChange(this).call(this, e);
},
render: function() {
var props = filterKeys(this.props, ["valueLink"]);
return Component(defaults({
value: this.state.value,
onChange: this.handleChange,
onBlur: this.handleFormat,
}, props));
},
});
function format(value) {
if (options.format) {
return options.format.call(this, value);
}
return value;
}
function unformat(value) {
if (options.unformat) {
return options.unformat.call(this, value);
}
return value;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment