Daniyal Shaikh
Daniyal Shaikh

Reputation: 418

TextInput that only accepts certain input of user without flickering issues

I have a textinput lets say :

<TextInput
maxLength={5}
onChangeText={val => {
  setExpiry(val.replace(/[^0-9]/g, ''));
}}
placeholder="Input"
value={Expiry}
keyboardType={'default'}/>

I want to restrict user to only add numbers, or any specific format using regex or simple loops.

The above is achieved, working without any functional issues.

But what seems to be off about this method is that it takes a little time (1ms may be) when you enter something unwanted, it shows entered character then removes that character. Overall, this doesn't look that great when it comes to user experience.

What I have tried:

  1. Loop through the input and remove unwanted characters

It works but is slow and give the above flickering issues.

  1. Use regex to replace with empty string

It works and is better at performance than above method, but still it gives the flickering issue.

So My question is that is there any other way to have the same text box as on a native platform that doesn't have this flickering issue.

For Example: On native android, this issue is not faced.

References:

Regexp with textinput

Loop with textinput

Issue in GitHub repo

Handling TextInput Docs

Upvotes: 1

Views: 587

Answers (1)

Abe
Abe

Reputation: 5508

If the requirement is to allow only numbers, using keyboardType='numeric' will eliminate everything besides numbers (and some punctuation on Android, see the docs on TextInput). Your regex solution will still be required to prevent non-number content, but it should be used less this way.

Have you tested your flickering issue on a release build of your app? The debug version will always be slower, and the flickering problem may not exist in a release build.

Upvotes: -1

Related Questions