Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect a paste event in a react-native text input

I want to paste into a react native input, but do something based on the pasted content (i.e. if the pasted content is a link, style it accordingly). However, in order to do this I need to know when something has been pasted into the text input. I am not sure how to listen for a paste event. The Clipboard does not really help here because all it does it set/get content, not tell me if some arbitrary content has been pasted.

like image 779
nmac Avatar asked Sep 07 '16 14:09

nmac


2 Answers

For people who come across this post from Google, and found no luck like me, fortunately, I found the solution although not ideal because it use onChangeText event.

The idea is simple, every time the text is changed, I will compare it with content from the clipboard. That's it.

The minimal sample code

export default class App extends React.Component {
  handleOnPaste = (content) => {
    alert('paste detected! content: '.concat(content));
  }

  handleOnChangeText = async (content) => {
    if (content === '') return;
    const copiedContent = await Clipboard.getString();
    
    if (copiedContent === '') return;
    const isPasted = content.includes(copiedContent);
    if (isPasted) this.handleOnPaste(content);
  }

  render() {
    return (
      <View style={styles.container}>
        <TextInput 
          placeholder={'fill something'} 
          style={styles.input} 
          onChangeText={this.handleOnChangeText} 
        />
      </View>
    );
  }
}

here is the snack expo, enjoy!

enter image description here

like image 130
I Putu Yoga Permana Avatar answered Sep 23 '22 07:09

I Putu Yoga Permana


You can keep 2 copies of the input in state, with 1 copy being the previous state of the input and the other being the state of the current input. Example being

Actual input: asd
this.state={copy_one: "as", copy_two: "asd"}

Actual input: asdgoogle.com
this.state={copy_one: "asd", copy_two: "asdgoogle.com"}

You can update them by doing

this.setState({copy_one: this.state.copy_two, copy_two: currentValue})

on every trigger of the onChange prop. If you're specifically looking for the changes, a quick and dirty hack to get only the difference would be do delete the original string via replacement

difference = this.state.copy_two.replace(this.state.copy_one, "")

then you can use regex to see if it's a link and stylize it accordingly.

like image 21
Nerdragen Avatar answered Sep 24 '22 07:09

Nerdragen