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.
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!
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With