Clearing TextInput with React Native
While developing a chat feature in a React Native app, I was attempting to create a TextInput component that would clear automatically after a submit button was pressed. It appears some methods included with React Native are not functioning correctly in certain environments when it comes to this task. Since I could not find an appropriate solution elsewhere, I figured I’d share my work-around for this problem.
For the tl;dr crowd, here’s the solution:
submitAndClear = () => {
this.props.writeText(this.state.text) this.setState({
text: ''
})
}
Getting Started
Let’s start by setting up a simple app that allows a user to enter text that gets displayed in the app.
We’ll assume you already have React Native up and running with all necessary requirements installed (Node JS, Watchman, etc…). Note: I’d recommend using Node v8.x.x while working with React Native v0.x.x.
We’re going to get this project started with Expo. If you’re unfamiliar with Expo, checkout their documentation! Expo installation:
npm i -g expo expo-cli
With Expo, we can initialize our project named clear-text
, and cd
into that directory: