var Input = React.createClass({
render: function() {
return <input ref="root" {...this.props} value={undefined} />;
},
componentDidUpdate: function(prevProps) {
var node = React.findDOMNode(this);
var oldLength = node.value.length;
var oldIdx = node.selectionStart;
node.value = this.props.value;
var newIdx = Math.max(0, node.value.length - oldLength + oldIdx);
node.selectionStart = node.selectionEnd = newIdx;
},
});
var MoneyInput = React.createClass({
getInitialState() {
return {
money: ''
};
},
formatThousandth(amount) {
if (!!amount) {
return amount.replace(/(\d)(?=(\d{3})+(?:\.\d+)?$)/g, "$1,");
} else {
return amount;
}
},
parseThousandth(amountStr) {
return amountStr.replace(/,/g, '')
},
onChange(e) {
let money = this.parseThousandth(e.target.value)
let moneyThousandth = this.formatThousandth(money)
console.log(e.target.value + ' ' + money + ' ' + moneyThousandth);
this.setState({
money: moneyThousandth
});
this.props.onInputChange(money);
},
render: function() {
return (
<div><Input onChange={this.onChange} value={this.state.money}/></div>
)
}
})
var MoneyInputDemo = React.createClass({
getInitialState() {
return {
money: undefined
};
},
onInputChange(changedMoney) {
this.setState({
money: changedMoney
});
},
onSubmit() {
alert('Money is ' + this.state.money);
},
render: function() {
return (
<div>
<MoneyInput onInputChange={this.onInputChange} />
<button onClick={this.onSubmit}>Submit</button>
</div>
);
}
});
React.render(<MoneyInputDemo />, document.getElementById('container'));
External resources loaded into this fiddle:
<script src="https://facebook.github.io/react/js/jsfiddle-integration.js"></script>
<div id="container">
<!-- This element's contents will be replaced with your component. -->
</div>