To copy text into the clipboard using JavaScript, you can use the Clipboard API:
The navigator.clipboard.writeText function accepts the text to copy, and returns a Promise:
resolved - if the text was copied successfully,
rejected - if the user hasn't given the "clipboard-write" permission.
Using Clipboard API in React
You can use the above JavaScript code to implement copying to the clipboard in React, but it's helpful to create a custom hook:
The hook returns a tuple with the function to copy text into the clipboard and an object describing the result:
null - no text copied recently;
"success" - text copied successfully;
"error" - operation failed with the error message.
You can use the useCopyToClipboard hook like this:
The copy operation has no inherent feedback in the UI, so it's a good idea to provide it yourself, you can do that by checking the copyResult value.
Here's what it looks like:
Copy to clipboard button in React
You can also create a CopyToClipboard button component in React that accepts a text prop and handles showing the feedback messages in the UI. Here's an example that uses react-hot-toast:
Feel free to use the native alert function instead of the toast messages. In that case, replace the toast calls with alert('your message'). However, if you use react-hot-toast you also need to add the Toaster component. Here's an example:
Here's what it looks like now:
Conclusion
The simplest way to copy text to the clipboard in JavaScript is by using the Clipboard API. It has good support in modern browsers and it's easy to use.
However, in case you need to support older browsers you can use the copy-to-clipboard npm package, which falls back on using execCommand in case the browser doesn't have access to navigator.clipboard object.
Read about how to get values from the input fields in React next: