header banner

How to Include the Copy to Clipboard Function in Your React Application

Learn how to incorporate this useful feature into your React app using the Clipboard API and the react-copy-to-clipboard library.

Close up shot of copy buttons

Manually copying information, be it code snippets, URL links, or text fragments can be time-consuming and error-prone, especially on mobile devices where the screen is small. Adding a “copy to clipboard” functionality not only saves time but also reduces the potential for errors and typos.

Setting Up the Copy to Clipboard Functionality

In a React app, create a new component named CopyButton. This component accepts text that it should copy to the clipboard.

If you don’t have a React project to work on, use the create react app utility to scaffold one.

 function CopyButton({text}) {
    const copyToClipboard = () => {
        // copy to clipboard
  return (
    <button onClick={copyToClipboard}>Copy</button>

export default CopyButton

When clicked, the button should call a function named copyToClipboard that copies the text to the clipboard.

To implement the copy functionality, you can use the clipboard API directly or use an NPM package.

This guide will show you how to use both.

Using the Clipboard API to Copy Text to a Clipboard in React

The Clipboard API provides a way to interact with clipboard commands such as copy, cut, and paste.

To access it, you need to use the navigator.clipboard object available in most modern browsers. It has several methods that allow you to write or read the contents of the clipboard.

To write to the clipboard, use the writeText method.

Let’s see how to implement this in the copyToClipboard function of the CopyButton component.

 const copyToClipboard = async (text) => {
    try {
      await navigator.clipboard.writeText(text);
      alert('Text copied to clipboard:', text);
    } catch (error) {
      alert('Error copying to clipboard:', error);

The writeText method accepts the text that it will copy to the clipboard. This method is asynchronous, so you have to use the await keyword before moving on.

If the text is copied to the clipboard, display a success message otherwise display the error message as an alert.

Checking Browser Permissions

As good practice, it’s important to ensure that the user has granted the browser permission to access the clipboard. You can check if the user has granted clipboard-write permission using the navigator.permissions Web API before copying to the clipboard as shown below.

 const copyToClipboard = async () => {
    try {
        const permissions = await navigator.permissions.query({name: "clipboard-write"})
        if (permissions.state === "granted" || permissions.state === "prompt") {
            await navigator.clipboard.writeText(text);
            alert('Text copied to clipboard!');
        } else {
            throw new Error("Can't access the clipboard. Check your browser permissions.")
    } catch (error) {
        alert('Error copying to clipboard:', error);

In the modified function above, only when the user has granted permission to write to the clipboard are writing to it. Otherwise, the function throws an error.

Using an NPM Package to Copy to Clipboard in React

If you don’t want to use the clipboard API directly, there are multiple NPM packages you can use instead. For react applications, you can use the react-copy-to-clipboard package. It’s pretty popular with more than 1 million weekly downloads and is also easy to use.

Install it in your React application by running the following command in the terminal:

 npm install react-copy-to-clipboard

Once installed, import the CopyToClipboard component from react-copy-to-clipboard into the CopyButton component.

 import {CopyToClipboard} from 'react-copy-to-clipboard';

The CopyToClipboard component accepts the text you want to copy as a prop. It also accepts a child component that when clicked triggers the copy action.

For instance, use the code below to copy to the clipboard with a button:

 <CopyToClipboard text={text} onCopy={(text, result) => console.log(result)}>

Note the handler function, onCopy. It accepts two arguments, text and result where text is the copied text and the result is a boolean indicating whether the copy action was successful or not.

Why Use a Copy to Clipboard Function?

You’ve learned how to use the clipboard API and the react-copy-to-clipboard package to copy text to the clipboard in a React application. While the users of your application can simply select the text and use the copy functionality of your browser, clicking to copy text is more straightforward and better for the user experience.


Article information

Author: Mr. Kevin Smith

Last Updated: 1704092882

Views: 732

Rating: 3.5 / 5 (48 voted)

Reviews: 82% of readers found this page helpful

Author information

Name: Mr. Kevin Smith

Birthday: 1949-06-13

Address: 5465 Cortez Haven Apt. 249, Lake Kathleenville, MA 58060

Phone: +4334459912526901

Job: Pharmacist

Hobby: Sculpting, Crochet, Graphic Design, Cocktail Mixing, Role-Playing Games, Playing Guitar, Kite Flying

Introduction: My name is Mr. Kevin Smith, I am a unyielding, treasured, skilled, audacious, honest, exquisite, resolute person who loves writing and wants to share my knowledge and understanding with you.