Last active
August 29, 2015 13:57
-
-
Save parshap/9420847 to your computer and use it in GitHub Desktop.
React input formatting
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** @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