Skip to content

Instantly share code, notes, and snippets.

@parshap
Last active August 29, 2015 13:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save parshap/9420847 to your computer and use it in GitHub Desktop.
Save parshap/9420847 to your computer and use it in GitHub Desktop.
React input formatting
/** @jsx React.DOM */
"use strict";
// An <input /> component that applies a format function to the value
// on initial render and when the element loses focus.
//
// Usage:
//
// <FormattedInput format={Math.round} valueLink={this.linkState("value")} />
//
var React = require("react");
var type = require("core-util-is");
var LinkedStateMixin = require("react/lib/LinkedStateMixin");
module.exports = React.createClass({
mixins: [LinkedStateMixin],
getInitialState: function() {
var value = String(this.props.valueLink.value);
return {
value: this.applyFormat(value),
};
},
componentWillReceiveProps: function(props) {
var value = props.valueLink.value;
this.setState({ value: this.applyFormat(value) });
},
applyFormat: function(value) {
if (type.isFunction(this.props.format)) {
return this.props.format.call(null, value);
}
return value;
},
setValue: function(value) {
this.props.valueLink.requestChange(value);
},
format: function() {
this.setValue(this.applyFormat(this.state.value));
},
render: function() {
return this.transferPropsTo(
<input onBlur={this.format} valueLink={this.linkState("value")} />
);
},
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment