skip to Main Content

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


  1. Chosen as BEST ANSWER

    After thinking it over more I realized that using onKeyPress with onChangeText is overkill. I can simply use onKeyPress to check for commas:

    const testChange = (e) => {
      if (e.includes(',')) {
        setTagValue('')
      } else {
        setTagValue(e)
      }
    }
    
    <TextInput
      ...
      onChangeText={(e) => testChange(e)}
      ...
    />
    

  2. change createRef to useRef

    const tRef = React.useRef()
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search