s-yadav / react-number-format

React component to format numbers in an input or as a text.
MIT License
3.88k stars 409 forks source link

React-Native Support #17

Open indivisable opened 7 years ago

indivisable commented 7 years ago

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
s-yadav commented 7 years ago

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.

ivanzotov commented 7 years ago

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.

s-yadav commented 7 years ago

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.

ivanzotov commented 7 years ago

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

Jeffliu commented 7 years ago

Any progress on React Native support?

afilp commented 6 years ago

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

drew-sullivan commented 6 years ago

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>
questionablequestion commented 6 years ago

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
/> 
DrJid commented 6 years ago

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 })
  }
baranoveyy commented 5 years ago

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

<NumberFormat 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 <NativeTextInput 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

thegoldenmule commented 5 years ago

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?

goskan93 commented 5 years ago

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.

dnlnvl commented 5 years ago

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.

khalidchawtany commented 4 years ago

@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"
            />
        );
      }
    }
/>
zmnv commented 4 years ago

@khalidchawtany

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

rohandayal commented 4 years ago

@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" /> ); } } />

samuelpetroline commented 4 years ago

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?

cenaHara commented 3 years ago

same issue @samuelpetroline any solution ?

samuelpetroline commented 3 years ago

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

cenaHara commented 3 years ago

hi @samuelpetroline Thank you, but when I use this lib, number jumps when input, will you be the same as me <TextInputMask 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: '' }} />

MuhammadSalmanSiddiqui commented 3 years ago

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

ivanchauma commented 3 years ago

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

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

brisingrBase commented 3 years ago

@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