Home > front end >  React Native - Continuous textinput delete on Pressable longpress
React Native - Continuous textinput delete on Pressable longpress

Time:11-17

I have this little concern wherein when I tried to do a onLongPress with Pressable. the function associated to that are only called once.

How can I have it continuously delete the value on textInput when I hold the pressable?

Sample Code:

<Pressable
              style={({ pressed }) => [
                styles.deleteStyle,
                {
                  opacity: pressed
                    ? 0.5
                    : 1,
                }]}
              onPress={() => { delDigit() }}
              onLongPress={() => { delDigit() }}
            >
              <Icon style={[{ color: '#FD6B89' }]} name="backspace" size={30} />
            </Pressable>

Thanks in advance!

CodePudding user response:

A very simple solution is to use a setInterval function when the onLongPress function is called when you hold down the Pressable button. And you can use clearInterval to stop the deletion of text from your textInput.

Steps:

a) Call a setInterval function on Pressable when the onLongPress function is called and in each interval delete the last element of the string of your value from textInput.

onLongPress={() => {
   this.timer = setInterval(() => {
      this.setState({
          email: this.state.email.substring(0,this.state.email.length - 1)
      })
   },200)
}}

b) Call a clearInterval function on Pressable when the onPressOut function is called to clear the timerInterval declared in onLongPress

    onPressOut={() => {
      clearInterval(this.timer)
    }}

Here is a full working solution/example for your issue: https://snack.expo.dev/@gavindmello97/pressable-deletion

Hope that helps you. If it did, kindly mark my answer as the correct answer so others can benefit from it as well. Drop me a message/ comment if you are facing any issues with my code. Happy to help you out.

  • Related