react-native icon indicating copy to clipboard operation
react-native copied to clipboard

Can't modify text in TextInput onChangeText callback on Android

Open rogerbright opened this issue 6 years ago • 65 comments

🐛 Bug Report

On Android, modifying the text within the onChange (or onChangeText) callback causes corruption of the text in the TextInput. (Not tested on iOS.)

For example, I'm trying to force all caps in my TextInput field. (This is to work around the react native autoCapitalize issue described here: https://github.com/facebook/react-native/issues/8932). So if a lowercase letter is entered, I change it to uppercase in the callback. Unfortunately, alternate keystrokes cause the entire previous text to be duplicated, but only if the entered keystroke was lowercase.

So, when forcing all caps, entering 1234 results in 1234 showing up; entering ABCD results in ABCD showing up; but entering abcd results in AABCAABCD.

This issue disappears if assigning a Math.random() key to the TextInput; but then of course so does the keyboard focus, making this an unacceptable workaround.

To Reproduce

See "Bug Report" and "Code Example" sections.

Expected Behavior

One should be able to modify the value inside TextInput's change callbacks, without the text becoming corrupted on the subsequent redisplay.

Code Example

export default class TestScr extends Component
{
  constructor(props)
  {
	super(props);
	this.state = { s6: '' };
  }
  textchg(event)
  {
	const {eventCount, target, text} = event.nativeEvent;
            // one would expect the contents of s6 to display after the redraw
	this.setState({ s6: text.toUpperCase() }); 
  }
  render()
  {
            // [same behavior if using onChangeText instead of onChange]
	let jsx0 = <View style={{ flexDirection: 'row' }} key={ 'hi' }>
		<TextInput placeholder={ 'hello' } value={ this.state.s6 }
			onChange={ (evt) => this.textchg(evt) }
			keyboardType={ 'default' } />
		</View>;
		
	return (<View style={{ backgroundColor: '#ffffff', padding: 10, }}>
		<ScrollView style={{ backgroundColor: '#ffffff', }}>
			{ jsx0 }
		</ScrollView>
	</View>);
  }
}

Environment

React Native Environment Info: System: OS: Linux 3.19 Ubuntu 14.04.3 LTS, Trusty Tahr CPU: (4) x64 Intel(R) Core(TM) i7-5500U CPU @ 2.40GHz Memory: 626.14 MB / 15.38 GB Shell: 6.18.01 - /bin/tcsh Binaries: Node: 8.11.3 - /usr/bin/node npm: 5.6.0 - /usr/bin/npm SDKs: Android SDK: API Levels: 10, 16, 23, 26, 27, 28 Build Tools: 19.1.0, 20.0.0, 21.1.2, 22.0.1, 23.0.1, 23.0.2, 26.0.3, 27.0.3, 28.0.2, 28.0.3 System Images: android-16 | ARM EABI v7a, android-23 | Intel x86 Atom_64, android-23 | Google APIs Intel x86 Atom_64, android-28 | Google APIs Intel x86 Atom npmPackages: react: 16.6.3 => 16.6.3 react-native: 0.58.6 => 0.58.6 npmGlobalPackages: create-react-native-app: 1.0.0 react-native-cli: 2.0.1

rogerbright avatar Feb 21 '19 19:02 rogerbright

It looks like you are using an older version of React Native. Please update to the latest release, v0.58 and verify if the issue still exists.

The "Resolution: Old Version" label will be removed automatically once you edit your original post with the results of running react-native info on a project using the latest release.

react-native-bot avatar Feb 21 '19 19:02 react-native-bot

Shouting into the wind! Hope the next person can use this as a basis for reporting the issue.

rogerbright avatar Feb 21 '19 20:02 rogerbright

Sorry about that, but it's really important to make sure the issue is present in the latest release. We've had plenty of issues reported for bugs that have been fixed already.

For bug reports that have a minimal repro example, verifying on the latest version using a brand new project should not take a lot of effort.

hramos avatar Feb 21 '19 23:02 hramos

Unable to replicate: https://snack.expo.io/@jkcooper/rn-issue-#23578---textinput-on-change

CatapultJesse avatar Mar 02 '19 00:03 CatapultJesse

Still happening on latest release. I've updated the react-native info text in the description.

rogerbright avatar Mar 02 '19 13:03 rogerbright

@rogerbright is this happening in emulator, or on device?

ericlewis avatar Mar 02 '19 13:03 ericlewis

Tested just now on both an emulator (Nexus 5X API 28) and an actual device (Galaxy Tab A SM-T580). Same results on both.

rogerbright avatar Mar 02 '19 13:03 rogerbright

Would you be able to setup a snack demonstrating this issue? On Mar 2, 2019, 8:46 AM -0500, rogerbright [email protected], wrote:

Tested just now on both an emulator (Nexus 5X API 28) and an actual device (Galaxy Tab A SM-T580). Same results on both. — You are receiving this because you commented. Reply to this email directly, view it on GitHub, or mute the thread.

ericlewis avatar Mar 02 '19 13:03 ericlewis

Sure.

https://snack.expo.io/By1LO7uUV

In the snack interface, the bug appears only on Android. Works correctly on iOS. Make sure you enter only lowercase letters.

rogerbright avatar Mar 02 '19 16:03 rogerbright

@rogerbright ty I will take a look at this!

ericlewis avatar Mar 02 '19 20:03 ericlewis

I am facing the same issue. I have explain the isuue here https://github.com/facebook/react-native/issues/23663#issuecomment-471537331

umair-khanzada avatar Mar 11 '19 13:03 umair-khanzada

@umair-khanzada your issue seems different. In my case, the callbacks are being called just fine... it's what happens when I modify the text that makes things screwy.

rogerbright avatar Mar 13 '19 18:03 rogerbright

Thanks @ericlewis for volunteering to fix it! I think this is really annoying and severe issue, but fortunately, it's not affecting many of our developers.

I am going to label this "mid-pri" while we are waiting for the PR.

grabbou avatar Mar 19 '19 11:03 grabbou

this happens with setNativeProps directly as well: https://github.com/facebook/react-native/issues/24409

brentvatne avatar Apr 11 '19 15:04 brentvatne

Can confirm this also happens on RN 0.59 as well. Looks like I didn't need to modify controlled text input in a while, but when I did I remember using an overlay over transparent uncontrolled text input that would display the transformed text. I'd say it's pretty serious bug (and pretty old, happens at least since 0.57).

thymikee avatar Apr 11 '19 16:04 thymikee

here's a video of a repro: https://streamable.com/j4s4r

and the code (i tested this on 0.57 and 0.59):

import * as React from 'react';
import { Text, TextInput, View, StyleSheet } from 'react-native';

class ControlledInput extends React.Component {
  state = {
    value: '',
  };

  _handleChangeText = ({ nativeEvent: { text } }) => {
    this.setState({ value: text.toUpperCase() });
  };

  render() {
    return (
      <TextInput
        style={{
          width: 300,
          height: 50,
          padding: 10,
          backgroundColor: '#fff',
          borderWidth: 1,
          borderColor: '#eee',
          borderRadius: 2,
        }}
        onChange={this._handleChangeText}
        value={this.state.value}
      />
    );
  }
}

export default class App extends React.Component {
  render() {
    return (
      <View style={styles.container}>
        <ControlledInput />
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    backgroundColor: '#ecf0f1',
    padding: 8,
  },
});

and a snack: https://snack.expo.io/@notbrent/ranting-sandwich

brentvatne avatar Apr 11 '19 17:04 brentvatne

Any ideas for a workaround?

slavikdenis avatar Jun 17 '19 11:06 slavikdenis

You could mess around with a Math.random() key for the input field. This blurs the focus after each keystroke though, so you'd have to write code to re-focus and move the cursor to the end. Personally, I no longer modify the input at all on Android, and instead just do the all-caps (or whatever) on the back end before saving to the DB. Not the best user experience. It's too bad the RN team seems uninterested in fixing pretty major issues like this one, and instead seems to spend their time making breaking changes to APIs, moving things arbitrarily out of the core APIs, etc.

rogerbright avatar Jun 17 '19 11:06 rogerbright

method: <TextInput autoCorrect={false} />

xdcheng avatar Jul 12 '19 08:07 xdcheng

@slavikdenis @rogerbright @thymikee @umair-khanzada I have two different solutions. They aren't exactly adequate for all scenarios. Text selection being one of them. But hopefully they will be of some use: https://snack.expo.io/@509dave16/android-text-input-out-of-sync-solutions

A text input component that displays a mask over the actual text input. And a text input that extracts the correct value from the onChangeText, which is providing an out of sync value from the native side.

509dave16 avatar Aug 12 '19 04:08 509dave16

@hramos I have created a new more up to date issue on this. If you would like for de-duplication purposes, I could move all of the content from this #26017 over here to a comment. Let me know what you think.

509dave16 avatar Aug 12 '19 16:08 509dave16

My report of this bug

Summary

When attempting to ignore certain characters by controlling the state value that's passed to the TextInput, the TextInput's natively held value get's out of sync. This makes it impossible to enforce a particular text pattern at the time of a user entering the text. This exact issue was occurring before React Native 57.1 on iOS, as noted here in this now closed issue #18874 .

React Native version: 0.59.8(based on Expo SDK 34)

Steps To Reproduce

  1. Implement an onChangeText event handler that will selectively choose to not update the state value(which control's the TextInput's natively stored value). For example, let's say uppercase letters like 'A', 'B', 'C', etc...
  2. Enter characters other than the ones to be ignored
  3. Enter at least 1 or more of the ignored characters
  4. Go back to entering characters other than the ones to be ignored

Describe what you expected to happen:

  1. Enter 'abc', resulting in 'a', 'ab', and 'abc' being passed to onChangeText handler each of which are valid and are set on the state value that controls the TextInput.
  2. Enter 'A' which should be ignored, thus 'abcA' will not be set on the state value that controls the TextInput. Meaning only 'abc' is still displayed in the TextInput.
  3. Enter 'd', which should result in onChangeText handler receiving 'abcd' which is valid and will be set on the state value that controls the TextInput.

Snack, code example, screenshot, or link to a repository

  1. Snack here
  2. Screenshots that follow the steps outlined in the Describe what you expected to happen section above. Notice after entering 'A' that a pattern emerges in the natively held text value. It concatenates the characters that have been entered to the state controlled value that has remained at 'abc' since the character 'A' was entered.
    • Enter 'a'
    • Enter 'b'
    • Enter 'c'
    • Enter 'A'
    • Enter 'b'

509dave16 avatar Aug 15 '19 22:08 509dave16

Exists in react-native 0.59.10 too.

anees-syook avatar Oct 14 '19 12:10 anees-syook

I am not sure if this would also work on IOS, but it solved the problem for me on Android. The answer is quite simple: NEVER use value when rendering a TextInput. Use defaultValue instead.

If this turns out to really fix the issue for every platform, maybe we could just issue a warning every time someone uses value as a prop to TextInput.

UPDATE: I've tried this in iOS, and it also works.

lgenzelis avatar Oct 30 '19 21:10 lgenzelis

@lgenzelis, thanks! So what value is good for again?

moshfeu avatar Dec 24 '19 23:12 moshfeu

Hey there, it looks like there has been no activity on this issue recently. Has the issue been fixed, or does it still require the community's attention? This issue may be closed if no further activity occurs. You may also label this issue as a "Discussion" or add it to the "Backlog" and I will leave it open. Thank you for your contributions.

stale[bot] avatar Mar 26 '20 03:03 stale[bot]

This is still affecting me.

Aetf avatar Mar 26 '20 18:03 Aetf

yeah this is still an issue as far as i know

brentvatne avatar Mar 28 '20 19:03 brentvatne

defaultValue doesn't solve the problem. If you want to mask user inputs and show user masked inputs, still have to use value prop.

IngyuTae avatar Apr 07 '20 16:04 IngyuTae

Still an issue.

saulojoab avatar Apr 23 '20 15:04 saulojoab