1

How to make a React Native TextInput accept only numbers and make it accept numbers 1 to 10 only?

For example, say I input 11, the value should automatically change into the maximum allowed, that is, 10.

And when I input 0, the value should automatically change into the minimum allowed, that is, 1.

As of now the only thing I have done are:

<TextInput
style={styles.input}
placeholder="Maximum of 10 passengers only"
maxLength={2}
keyboardType={"numeric"}
/>
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
serking
  • 111
  • 8

1 Answers1

2

You can use this:

...
const [value, setValue] = React.useState(0);
....

  React.useEffect(() => {
    if(value === "") {
      return;
    }
    if(+value > 10) {
      setValue(10)
    } else if (value < 1) {
      setValue(1);
    }

  },[value])


<TextInput
      keyboardType='numeric' 
      maxLength={2}
      value={value.toString()} 
      onChangeText={(e) => {
      setValue(e)
    }} />