I'm trying to create a currency input, that starts as something like
" $00.00"
and then when you start typing, it types the cents first, then moves on to the dollars (ie, updates the right side numbers first), e.g
" $00.50"
So far I have it implemented, where the user types in one box, and the correctly formatted output displays in a second box.
Code :
constructor(props) {
super(props);
this.state = {
amount: '',
};
}
formatValue(value) {
return accounting.formatMoney(parseFloat(value) / 100, "$ ");
}
render() {
return (
<ScrollView>
<Text style={styles.text}> Enter the Amount to be payed</Text>
<TextInput
onChangeText={(amount) => this.setState({amount})}>
</TextInput>
<TextInput
onChangeText = {amount => this.setState({amount})}
value={this.formatValue(this.state.amount)}>
</TextInput>
</ScrollView>
);
}
However, I want the currency formatting to apply to the same box the user is typing into. I have tried something like this:
<TextInput
onChangeText={(amount) => this.setState({amount})}
value = {this.formatValue(this.state.amount)}>
</TextInput>
but this simply sets the input to zero, and it cannot be changed. I am clearly not understanding this correctly.
Does anyone have any insight on this?
I needed to do this exact thing in a recent project and I ended up releasing it as an npm package.
https://github.com/wwdrew/react-native-numeric-textinput
It uses the Intl NumberFormat for formatting currencies and numbers, so should work for any currency you want to throw at it.
Maybe this package can help you out. It lets you store change value in state.
https://www.npmjs.com/package/react-currency-input
Or since you only want to mask the input and not do any mutation/converting to the input you can of course do something like this;
https://www.npmjs.com/package/react-input-mask
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With