Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React-native currency input

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?

like image 989
Razor88 Avatar asked Jun 08 '17 13:06

Razor88


2 Answers

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.

like image 103
Drew Avatar answered Sep 28 '22 04:09

Drew


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

like image 24
daskel Avatar answered Sep 28 '22 03:09

daskel