Search code examples
reactjsreact-nativenumberstextinput

React native MAX value of number in Textinput


I am creating an input field for numbers in react native. in the text field, we can use the maxLength for characters. but I wanna max value of the number in this field.

for example when I set the limit of number is 10 so the user can't put the 11 of number.

I don't know how to do this. please write your valuable comments or answer. thank you in advance


Solution

  • In your onChangeText prop you can pass a method just like:

      const onCheckLimit = (value: string) => {
        const parsedQty = Number.parseInt(value)
        if (Number.isNaN(parsedQty)) {
          setQuantity(0) //setter for state
        } else if (parsedQty > 10) {
          setQuantity(10)
        } else {
          setQuantity(parsedQty)
        }
      }
    /* React Wrapper */
            <Input
              value={quantity}
              onChangeText={onCheckLimit}
              otherProps
            />
    /*React Wrapper*/
    
    

    If the value passed is higher than the limit, it will set the value to the limit. Otherwise, simply set the value that the user entered