React-number-format: React-Native Support

Created on 19 Jan 2017  Â·  23Comments  Â·  Source: s-yadav/react-number-format

Will this work with react native?

I tried to install and got a Transform Error from Babel:

TransformError: /Users/XXX/node_modules/react-number-format/lib/number_format.js: 
[BABEL] /Users/XXX/node_modules/react-number-format/lib/number_format.js: 
Unknown option: /Users/XXX/node_modules/react/react.js.Children. 
Check out http://babeljs.io/docs/usage/options/ for more information about options.

A common cause of this error is the presence of a configuration options object without the corresponding preset name. Example:

Invalid:
  `{ presets: [{option: value}] }`
Valid:
  `{ presets: [['presetName', {option: value}]] }`

For more detailed information on preset configuration, please see http://babeljs.io/docs/plugins/#pluginpresets-options. (While processing preset: "/Users/XXX/node_modules/react/react.js")

RCTFatal + 124
-[RCTBatchedBridge stopLoadingWithError:] + 1124
__25-[RCTBatchedBridge start]_block_invoke_2 + 76
<redacted> + 24
<redacted> + 16
_dispatch_main_queue_callback_4CF + 1000
<redacted> + 12
<redacted> + 1660
CFRunLoopRunSpecific + 444
GSEventRunModal + 180
<redacted> + 684
UIApplicationMain + 208
main + 124
<redacted> + 4

Most helpful comment

To make this work with React Native all you have to do is to provide custom _renderText_ method:

import NumberFormat from 'react-number-format';

<NumberFormat
    value={2456981}
    displayType={'text'}
    thousandSeparator={true}
    prefix={'$'}
    renderText={value => <Text>{value}</Text>} <--- This
/> 

All 23 comments

It is not supported on react native yet. But I guess it should be an easy one to implement. I will be happy if someone can fork and work on react-native piece.

I was working on the similar module for React Native – https://github.com/ivanzotov/react-native-text-input-mask, it's not easy to implement text input mask in React Native, here I described why – https://blog.cloudboost.io/text-input-mask-for-react-native-3c04e82843a6
hope it helps.

Nice @ivanzotov. Is this only for masked input or does it have other formatting options?
And yes I agree that it will be not as easy as this library is depended a lot in input selection attributes, which I am not sure how much react-native provide.

@s-yadav thanks, yes it's only masked input yet, working on other options.

Any progress on React Native support?

Yes, we would like to have this for React Native, even for simple usage like adding a thousands separator.

I'm having what I think is a react-native issue. I'm using the example from the docs (and wrapping it in a Text component for some styling, omitted here). I'm getting:

"Invariant Violation: View config not found for name span", which means that the 'span' isn't capitalized, so I'm guessing the issue is with something that NumberFormat is doing under the hood? Any ideas? Thanks!

import NumberFormat from 'react-number-format'
<Text>
    <NumberFormat value={2456981} displayType={'text'} thousandSeparator={true} prefix={'$'} />
</Text>

To make this work with React Native all you have to do is to provide custom _renderText_ method:

import NumberFormat from 'react-number-format';

<NumberFormat
    value={2456981}
    displayType={'text'}
    thousandSeparator={true}
    prefix={'$'}
    renderText={value => <Text>{value}</Text>} <--- This
/> 

Just to add to @questionablequestion response, to get this working for an asYouType formatter, you can render a TextInput

              <NumberFormat
                value={amount}
                displayType={'text'}
                thousandSeparator={true}
                prefix={'$ '}
                renderText={value => (
                  <TextInput
                    underlineColorAndroid="transparent"
                    style={styles.input}
                    onChangeText={this.handleChange}
                    value={value}
                    keyboardType="numeric"
                  />
                )}
              />

where handleChange basically just changes state for your controlled component.
Ex

 handleChange = amount => {
    this.setState({ amount })
  }

NumberFormat component does not have a problem on web but in react native it doesnt work or i couldnt,
My configuration;

decimalSeparator=","
thousandSeparator="."
// isNumericString={true}
// allowNegative={false}
decimalScale={AMOUNT_FIELD_COMMA_INDEXES.ONE}
fixedDecimalScale={true}
// placeholder={${PLACEHOLDER.AMOUNT} ${this.props.currency}}
suffix={${this.props.currency}}
value={this.state.amountValue}
displayType={'text'}
renderText={(value) => {
return onChangeText={this.handleChange}
value={value}
keyboardType="numeric"
placeholder={${PLACEHOLDER.AMOUNT} ${this.props.currency}}
/>;
}
}
/>

And handleChange simple is
handleChange = (value) => {
this.setState({ amountValue: value}); }

In native cursor position changes after a new comma comes
When first number is entered cursor stay the end of input

I have the same issue as @baran10. Using @questionablequestion & @DrJid 's method I see the control but the caret is stuck at the end. I cannot backspace anything other than the last character. Are there caret settings I am missing?

An I have the same issue as @thegoldenmule .

My component looks like this

`

 <NumberFormat
        value={information.areasecure!= null ? information.areasecure: ""} 
        format="#.##"
        displayType={'text'}
        thousandSeparator={true}
        renderText={value => (
        <TextInput
               onChangeText={(value) => {this.setState({information: {...information, areasecure: value}})}}
               value={value}
               keyboardType="numeric"
        />
       )} 
 />

`

It looks like it renders few times, when i typ "1" I put the number "1" but then it render second time and add a space and looks like this "1 ". When add next number looks like "1.8 " (with space at the end). It is not possible to delete the characters.

Just to add to @questionablequestion response, to get this working for an asYouType formatter, you can render a TextInput

              <NumberFormat
                value={amount}
                displayType={'text'}
                thousandSeparator={true}
                prefix={'$ '}
                renderText={value => (
                  <TextInput
                    underlineColorAndroid="transparent"
                    style={styles.input}
                    onChangeText={this.handleChange}
                    value={value}
                    keyboardType="numeric"
                  />
                )}
              />

where handleChange basically just changes state for your controlled component.
Ex

 handleChange = amount => {
    this.setState({ amount })
  }

This works in terms of display but, for some reason, I can no longer input decimal places. It keeps deleting them. The thousandSeparator function works though.

@dnlnvl I can get around the issue of decimal places using the following:

<NumberFormat
    value={amount}
    displayType={'text'}
    thousandSeparator={true}
    decimalSeparator={'.'}
    decimalScale={2}
    prefix={''}
    renderText={value => {
        if (amount.endsWith('.') && !value.includes('.')) {
            value = value + '.';
        }
        return (
            <TextInput
                underlineColorAndroid="transparent"
                value={value}
                style={styles.textInput}
                onChangeText={handleAmountChange}
                keyboardType="numeric"
            />
        );
      }
    }
/>


@khalidchawtany

It's work only one direction. After '.' was added in value I can't delete '.'...

@khalidchawtany

It's work only one direction. After '.' was added in value I can't delete '.'...

Got it to work by extending @khalidchawtany 's approach. Basically, added another condition checker that removes the decimal when the passed value does not end with a decimal (found this by logging the values and checking what value is passed depending on various inputs). Not sure if all cases are covered though.

<NumberFormat value={amount} displayType={"text"} thousandSeparator={true} decimalSeparator={"."} decimalScale={2} prefix={""} renderText={value => { if (amount.endsWith(".") && !value.includes(".")) { value = value + "."; } if (!amount.endsWith(".") && value.endsWith(".")) { value = value.slice(0,-1); } return ( <TextInput underlineColorAndroid="transparent" value={value} style={styles.textInput} onChangeText={handleAmountChange} keyboardType="numeric" /> ); } } />

I have the same issue as @Baran10. Using @questionablequestion & @DrJid 's method I see the control but the caret is stuck at the end. I cannot backspace anything other than the last character. Are there caret settings I am missing?

I have the same problem. Did you find any solution to this?

same issue @samuelpetroline any solution ?

@cenaHara I ended up using react-native-masked-text

hi @samuelpetroline Thank you, but when I use this lib, number jumps when input, will you be the same as me
type={'money'}
placeholder={"$0.00"}
autoCorrect={false}
autoCapitalize="none"
keyboardType='decimal-pad'
returnKeyType="next"
value={value}
placeholderTextColor={ colors.GRAY}
style={[styles.inputStyle]}
maxLength={17}
onChangeText={handleChangeText}
options={{
precision: 2,
separator: '.',
delimiter: ',',
unit: '$',
suffixUnit: ''
}}
/>

on using suffix instead of prefix currency is overlapping over number, how can i resolve it?

@cenaHara I ended up using react-native-masked-text

I also ended up using this one, it's working fine, totally recommend

@khalidchawtany
It's work only one direction. After '.' was added in value I can't delete '.'...

Got it to work by extending @khalidchawtany 's approach. Basically, added another condition checker that removes the decimal when the passed value does not end with a decimal (found this by logging the values and checking what value is passed depending on various inputs). Not sure if all cases are covered though.

<NumberFormat value={amount} displayType={"text"} thousandSeparator={true} decimalSeparator={"."} decimalScale={2} prefix={""} renderText={value => { if (amount.endsWith(".") && !value.includes(".")) { value = value + "."; } if (!amount.endsWith(".") && value.endsWith(".")) { value = value.slice(0,-1); } return ( <TextInput underlineColorAndroid="transparent" value={value} style={styles.textInput} onChangeText={handleAmountChange} keyboardType="numeric" /> ); } } />

This works for me but it won't allow me to put a decimal point followed by a 0

for example 10.05 or 10.50 both won't work but 10.55 works fine

Was this page helpful?
0 / 5 - 0 ratings

Related issues

arpontes picture arpontes  Â·  7Comments

ddmedeiros picture ddmedeiros  Â·  6Comments

TkDodo picture TkDodo  Â·  5Comments

fedulovivan picture fedulovivan  Â·  6Comments

osvaldokalvaitir picture osvaldokalvaitir  Â·  3Comments