Jay0813
Jay0813

Reputation: 93

React Native TextInput maxLength not working after refocusing

I’m facing an issue with the maxLength property in React Native’s TextInput component.

The maxLength restriction works perfectly the first time I focus and type into the input. However, once I switch focus to another input or blur the current one, and then refocus on the original input, the maxLength no longer applies, allowing the user to type beyond the defined limit.

Here’s a summary of the issue:

When I first tap the TextInput to focus, the maxLength property works as expected. After switching focus to another input (or simply blurring and refocusing), the maxLength no longer restricts the input. Is this a known issue with React Native, or is there a workaround to ensure maxLength always applies, even after refocusing?

Any guidance or solutions would be greatly appreciated!

Upvotes: -1

Views: 95

Answers (1)

Hercule
Hercule

Reputation: 142

You can do this by adding an onFocus handler to the TextInput, ensuring that the property is enforced again when the input regains focus.

<TextInput
  value={yourValue}
  onChangeText={(text) => {
    if (text.length <= maxLength) {
      setYourValue(text);
    }
  }}
  onFocus={() => {
   // Reapply the maxLength here if needed
    setMaxLengthState(maxLength);
  }}
  maxLength={maxLengthState}
/>

Upvotes: 1

Related Questions