Ad

Bug In React Native TextInput When Using State On Android

- 1 answer

This bug only exists on Android.

If I have a textInput on Android and put value equal to state. Then somewhere else i change value, when i use onChange on the textInput it uses the old text value not the new state.

Here is my snack https://snack.expo.io/SyV1mkIc4

And below is the entire code showing it not working

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

// You can import from local files
import AssetExample from './components/AssetExample';

// or any pure javascript modules available in npm
import { Card } from 'react-native-paper';

export default class App extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      text:  'aaa'
    }
  }
  render() {
    return (
      <View style={styles.container}>
        <TextInput
          value={this.state.text}
          onChange={(event) => this.setState({
      text: event.text,
    })}
        />
      <TouchableOpacity
        onPress={()=>this.setState({
      text: "",
    })}
        style={styles.submit}
      >
      </TouchableOpacity>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    paddingTop: Constants.statusBarHeight,
    backgroundColor: '#ecf0f1',
    padding: 8,
  },
  submit: {
    height: 200,
    width: 200,
    backgroundColor: 'blue',
    textAlign: 'center',
  },
});
Ad

Answer

Okay i figured it out this a samsung only issue and has to do with keyboard caching. The solution is to keyboard.dismiss after changing the state of value.

Ad
source: stackoverflow.com
Ad