In my React Native app I want to clear the TextInput when the user hits the comma button. This will never clear the input. However, if I assign the same functionality to a Button component then it will work:
import React, { useState } from 'react'
import { Button, Text, TextInput, View } from 'react-native'
const COMMA = ','
const AddTags = () => {
const [ tagValue, setTagValue ] = useState('')
const tRef = React.createRef()
// THIS WONT WORK
const handleKeyDown = (event) => {
if (event.nativeEvent.key === COMMA) {
tRef.current.clear()
setTagValue('')
}
}
// THIS DOES WORK
const buttonPress = () => {
// You dont need both, either will work
tRef.current.clear()
setTagValue('')
}
return (
<View>
<Text>Add Tags</Text>
<Button onPress={buttonPress} title="Clear" />
<TextInput
onChangeText={setTagValue}
onKeyPress={handleKeyDown}
ref={tRef}
value={tagValue}
/>
</View>
)
}
export default AddTags
Not sure why it won’t clear onKeyPress but it will when the button is pressed. The code is exactly the same..
2
Answers
After thinking it over more I realized that using onKeyPress with onChangeText is overkill. I can simply use
onKeyPress
to check for commas:change
createRef
touseRef