Clear React Native TextInput
Working with the Redux AddTodo example in React Native. The first AddTodo example below uses state to store the TextInput value and works fine.
class AddTodo extends React.Component{
constructor(props){
super(props);
this.state = { todoText: "" };
}
update(e){
if(this.state.todoText.trim()) this.props.dispatch(addTodo(this.state.todoText));
this.setState({todoText: "" });
}
render(){
return(
<TextInput
value = {this.state.todoText}
onSubmitEditing = { (e)=> { this.update(e); } }
onChangeText = { (text) => {this.setState({todoText: text}) } } />
);
}
}
However, following a few Redux examples, the following code is much shorter and also works, except it is TextInput
value
not cleared after submission
let AddTodo = ({ dispatch }) => {
return (
<TextInput
onSubmitEditing = { e => { dispatch(addTodo(e.nativeEvent.text)) } }
/>
)
}
Is there a way to clear the InputText value from onSubmitEditing?
source to share
In accordance with the changes and recommendations emerged after the React 16.3 , you will need to get a link in your constructor using React.createRef:
In a constructor function: this.myTextInput = React.createRef();
When rendering the function:
<TextInput ref={this.myTextInput}/>
And then you can call
this.myTextInput.current.clear();
source to share
Following code example:
<TextInput
onChangeText={(text) => this.onChangeText(text)}
ref={component => this._textInput = component}
onSubmitEditing={() => {
this.clearText()
}}
/>
clearText(){
this._textInput.setNativeProps({ text: ' ' });
setTimeout(() => {
this._textInput.setNativeProps({ text: '' });
},3);
}
source to share
I am doing this code for clearing TextInput in React Native OnSubmitEditing
you can check my appetizer: 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>
)
}
source to share
One of the simpler approaches would be to use a property value
in TextInput
and use a component state value object to set the textInput value.
state = {
inputTextValue : '',
}
submitText = () => {
//handle the click action
//add this line at the end of the function after you are done handling with the input text value.
this.state.inputTextValue = '';
}
<TextInput
onChangeText={(text) => this.setState({ inputText: text })}
placeholder="Monday breakfast"
value={this.state.inputTextValue}
/>
<TouchableOpacity
onPress={() => this.submitText()}>
<Text>Submit</Text>
</TouchableOpacity>
source to share