React Native Basics: Copy to Clipboard
Reading and writing from the clipboard is incredibly easy in React Native by using the Clipboard API. In this quick tutorial we’ll build a simple app to read and write to it.
Starting App
To keep this tutorial simple we’ll start with a very basic app. It’s got two buttons, a TextInput, and some areas to render text.
Reading from the Clipboard
Let’s say you want to copy a password from the user’s clipboard — unless that text is going into an input the user can’t press and hold to copy it so we want to give them a simple button to copy it instead.
That’s where Clipboard.getString()
comes in. This function returns a promise with either the value or an error.
First, make sure you import { Clipboard } from 'react-native';
.
You can handle promises a few different ways but I’ll be opting to use async/await because it keeps are code very succinct.
Everything is already wired up (the button press will call the readFromClipboard
function) so we can just focus on interacting with the Clipboard API.
Since we’re using async/await we need to put async
in front of our function.
readFromClipboard = async () => {
alert('TODO: Read from Clipboard');
};
Then inside that function we’ll get the clipboard value and save it to state. Since getString
is a promise we need to wait for that value, which we can do by using the await
keyword.
readFromClipboard = async () => {
const clipboardContent = await Clipboard.getString();
this.setState({ clipboardContent });
};
That will then display the contents of the keyboard below “Clipboard Contents:”!
Try copying a contact’s name and the pasting it in the app.
Writing to the Clipboard
Writing to the clipboard is almost exactly the same so I’ll keep this one more brief. Once we successfully write to the clipboard we’ll alert that we did so to the user.
Note: The user could just as easily copy the value directly from the input, but where’s the fun in that?
First, make the function work with the await
keyboard by putting async
in front of it.
writeToClipboard = async () => {
alert('TODO: Write to the Clipboard');
};
We then want to write the value in our input to the clipboard and alert the user once it’s completed.
writeToClipboard = async () => {
await Clipboard.setString(this.state.text);
alert('Copied to Clipboard!');
};
Go ahead and copy something from your app, paste it into another app, or copy it to the clipboard and then read it from the code we wrote in the previous section!
And there we go! It’s a very simple API to work with but sometimes an example helps.
If you’re interested in learning other pieces of React Native — such as component design, navigation, redux, redux sagas, and more — check out my free course! It’ll save you a ton of time.