r/reactnative • • May 10 '19

TextInput which only accepts Integer?

Hi all,

I'm working on an app where I have multiple TextInputs, once numbers have been entered e.g: "2" and "3". Another Text field should update with "5".

This is proving to be an issue as TextInputs (as the name suggests) only seem to accept String values.

Is there another component I could be using or a setting to alter the input type of the TextInput component?

Many thanks!

14 Upvotes

14 comments sorted by

4

u/vinspee May 10 '19

You have to convert the value prior to doing the calculation.

2

u/wolfmojo May 10 '19

Ahh, that's what I feared. Thanks for the reply though, either way!

4

u/wolfmojo May 10 '19

Just to be clear, I know I can set keyboardType={'numeric'} but this still only allows me to input numbers as strings. The issue with strings is that I cannot do mathematics with them.

5

u/wise_introvert May 10 '19

onChangeText={stringNum => { this.setState({number: parseInt(stringNum)})}}

Sorry for the bad formatting.

6

u/lordkoba May 10 '19

NaN

5

u/wise_introvert May 10 '19

Did you set keyboardType={'numeric'}? If yes, then instead if setting state to parseInt(stringNum), use parseInt wherever you're using this.state.input

3

u/wolfmojo May 10 '19 edited May 10 '19

Yes I am* Thanks very much! I'll give this a go!

2

u/boomdoodle May 10 '19

Shouldn’t your parseInt have a base?

2

u/xrpinsider Admin May 10 '19

Yes it should.

2

u/[deleted] May 10 '19

You probably can easily convert this using unary plus.

Address it as +Numberstring and unary plus should coerce it into a number.

2

u/Mr_Chads May 10 '19

but it also allows accepting decimal values

2

u/TotesMessenger May 10 '19

I'm a bot, bleep, bloop. Someone has linked to this thread from another place on reddit:

 If you follow any of the above links, please respect the rules of reddit and don't vote in the other threads. (Info / ^Contact)

2

u/fvonhoven May 10 '19 edited May 10 '19

If you're looking to just get it done, you can check out Ramda's add function (https://ramdajs.com/docs/#add) which will accept two strings and add them with a resultant number, then you can just convert the result to a string like: String(R.add("2", "3")) --> "5"

Some might say you don't need such a big library for one function and that's true, but you can just destructure out the add function to cut down on the size during runtime, like:

import { add } from 'ramda' ​

then you can drop the R.:

String(add("2", "3")) --> "5"