Edit: Upon further inspection it seems that this only happens in Android 6.0.1. Having tried on several devices with 6.0, this was not an issue.
I have a very simple React Native code snippet where I want to clear text in a TextInput. It looks a little bit like this:
state = {
v: ""
};
_changeText = v => {
this.setState({ v });
};
clear = () => {
this.textInputRef.clear();
}
render() {
return (
<View style={styles.container}>
<TouchableOpacity onPress={this.clear}>
<Text> Clear </Text>
</TouchableOpacity>
<TextInput
ref={ref => this.textInputRef = ref}
value={this.state.v}
onChangeText={this._changeText}
/>
</View>
);
}
Now the behavior I would expect is for this to leave the text input in focus, and clear the text. This is what happens - however, the moment I start typing something on the keyboard, the text I have previously cleared reappears back in the Text Input. Obviously this sort of persistence of the text isn't really desired.
Have any of you ever encountered this issue? Is it a RN bug or is there any way to avoid this behavior without needing to blur the keyboard?
Here's a little snippet to clarify what I mean: https://snack.expo.io/H1S9b5Mpe.
If you start typing, press clear, then carry on typing, the previously shown text will appear before your newly typed text.
I have just finished struggling with this! Its a severe pain!
What i did to solve this (for now), was set the autocorrect prop of the TextInput to false, it seems like this prevents the keyboard from "maintaining a state"
<TextInput
autoCorrect={false}
ref={component => this.messageInput = component}
value={this.state.message}
onChangeText={(text) => this.setState({ message: text })}
placeholder="Type your message here..." />
I tried everything else and it seems like this is what worked. Looking forward to a better solution!
BTW: you should also do this.setState({ message: "" })
so that the value on the input is reset to an empty string.
I make this code for clearing TextInput in React Native OnSubmitEditing you can check my snack: https://snack.expo.io/@andreh111/clear-textinput-onsubmitediting
Here is the code:
state = {
searchInput:'',
clearInput:false
}
render(){
return(
<View style={{flex:1,justifyContent:'center',alignItems:'center'}}>
<TextInput
style={{
borderColor:'black',
borderWidth:1,
width:200,
height:50
}}
onChangeText={(searchInput)=>this.setState({
searchInput
})}
value={!this.state.clearInput ? this.state.searchInput : null}
onSubmitEditing={()=>{
this.setState({
clearInput:!this.state.clearInput,
})
}}
/>
</View>
)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With