React Copy to Clipboard Functionality

Learn via video courses
Topics Covered

Overview

The traditional way of copying text or code involves using the Ctrl+C key in windows or the Command+C key in Mac systems. This practice is easy for smaller text but can be optimized for longer text or code. This further optimization is usually done by using an event or a button that can copy text to the system's clipboard when clicked. React also has libraries that provide functions and hooks to copy text to a clipboard.

React Copy to Clipboard Functionality

The react copy to clipboard functionality can be used as a replacement for the copy shortcut key. The copy command is used to store text in the clipboard for a short period. The chipboard is a buffer space available in the RAM of the system and is usually overwritten when a new text is copied. In windows, when the copy command is used the SetClipboardData() function is called which stores the data in the clipboard buffer.

The functionality can be implemented with the react-copy-to-clipboard library and we will need to create a state using the useState() hook or a reference using the useRef() hook to store the text that is to be copied. Then components from the library have to be used to perform the copy operation which will be discussed in the next sections.

Implementation of Copy to Clipboard in React using Clipboard API

Prerequisites

There are no major prerequisites to implementing the React Copy to Clipboard functionality, but knowing the following things can make things very easy,

  • Usage of the npm package manager or yarn package manager to install external libraries and the npx command to create a react application.
  • Basic knowlege on the useRef() or useEffect() hook in react.
  • Understanding of events and states in react.

Modules Required

We can use the react-copy-to-clipboard module to create the React Copy to Clipboard functionality. The react-copy-to-clipboard package has the CopyToClipboard component that will be used to perform the copy operation. The component has the following props,

  • text - The text that is to be copied.
  • children- This is a required prop and involves all the children elements and components that will be rendered inside the CopyToClipboard component. The copy event can only be applied in this children element.
  • onCopy- A callback function that is invoked when the text is copied to the clipboard.
  • options- The options prop has other features that can be used. The debug option has a false value by default and can be set to true to print output to the console. The message option can be used to specify a prompt message. The format option can be used to specify the MIME type of content to be copied. For example, if we want to copy HTML files, we can set the format type to text/html.

The react-copy-to-clipboard package uses the copy function from @yarnpkg/plugin-interactive-tools which is a library that provides multiple functions that can interact with the operating systems.

It is important to note that we can specify only one child inside the CopyToClipboard component. This is due to the React.Children.only() function that is being used inside the component. The React.Children.only() function is used to verify if a component has a single child element and if there is more than one child, the function throws an error.

Correct Usage

Wrong Usage

We can use the #{key} keyword in the message option of the options prop to show the keys used to copy the text in respective systems. For example, the #{key} shows as Ctrl+C in windows and ⌘+C in Mac.

We can also use the usehooks-ts library to implement the React Copy to Clipboard function. The useCopyToClipboard hook in the library can be used to implement the copy function. The hook has a syntax similar to the useState() hook in react. The hook has a state and a function and can be implemented as follows,

The copy function is used to copy the text and the value is used to store the copied value. The useCopyToClipboard() hook uses the navigator.clipboard object to implement the react copy to clipboard feature. Information about the navigator object is discussed in the Clipboard API section.

Installation

The react-copy-to-clipboard can be installed using the npm package. The following command can be used to install the package,

If you are using the yarn package manager, you can install the package using the following command,

The usehook-ts library is written in typescript and can be installed with yarn or npm packet manager using the following command,

If you are using Typescript in your project, you will have to download the respective types along with the package. We can add the @types/ tag before the name of the package to add types for the package. We can install the types with npm using the following package,

About JavaScript Clipboard API

  • Javascript has a default Clipboard API to perform commands that read and write from the clipboard like cut, copy, and past. This can be utilized for the copy to clipboard react.
  • The navigator instance has information about the system and the user. The navigator.clipboard property passes the read-only property of the clipboard to the navigator object and returns a clipboard instance. This clipboard instance has the function to copy or paste text to the clipboard.
  • The clipboard instance is associated with the permission API to check if there are adequate permissions for the browser to access the clipboard of the system. There are two permissions, such as clipboard read and clipboard write associated with the clipboard object.
  • We can check the permissions using the query() function of the navigator.permissions interface.

The following javascript code can be used to perform a simple read or copy operation to the clipboard in a copy to clipboard react application,

All the functions of the navigator.clipboard instance are asynchronous and therefore can be chained using the then() and catch() functions.

To check permission on whether we can copy text to the clipboard, the following code can be used,

Explanation

  • The clipboard-write is the name of the permission that allows copy operation.
  • The query() function returns a promise that eventually resolves to the PermissionStatus object with a state that describes the results of the query.
  • The state can be any granted, prompt, or denied. The prompt state is usually present in cameras and microphones where the browser will ask the user for permission through a prompt message.
  • Similarly we can use the clipboard-read to check if we can read data from the clipboard in a copy to the clipboard react application.

We can also read text from the clipboard using the navigator.clipboard.readText() function. There is also a read() and write() function that can be used, if we want to read other data than text.

Before the clipboard API was introduced, the document.execCommand('copy') function can be used to copy text from a text field to the clipboard. The execCommand command is used to perform operations in editable fields. It is important to note that this function should not be used for the copy to clipboard react app as it is deprecated and is not supported in many browsers.

Basic Setup

A new copy to clipboard project can be created using the npx command.

The above command will take some time to run as it installs all the dependencies that are required for creating a react application and set the scripts that are required to run the react application to test locally and build the production application.

After the command is executed successfully, a new folder named name-of-react-app will be created and we can navigate to the folder using the cd command,

Structure of the Project

On exploring the folders, you can see the src folder in which all the coding should be done, and a public folder. The packages.json maintains a record of all the dependencies of the project.

We will keep a relatively simple project structure and create the example application in the App.js file. The index.js file has the code to render the component that is created in the App.js file to the browser.

structure of project example

Implementation

To create a react copy to clipboard application, we must install the react-copy-to-clipboard library using the npm package manager. This example uses the material UI library for implementing text fields, buttons, and snack bar elements.

Code: using the react-copy-to-clipboard library

Explanation

  • The CopyToClipboard is used to copy the text that is present in the text state when the button is pressed.
  • The copyState is set to true when the text is copied by the onCopy() function and this triggers a snack bar that closes automatically in three seconds.

We can also use the useCopyToClipboard hook from the usehooks-ts library to implement the copy to clipboard function in react. This library can also be installed using the npm library.

Code: Using the usehooks-ts library

Explanation

  • The useCopyToClipboard() hook has a copy() function to copy data and a value state to store the copied value.
  • The data in the text field is copied using the copy function when the button is pressed.
  • The snackbar is triggered after the text is copied and shows a success message along with the text copied.

We can also use the useCopy hook to perform the react copy to clipboard operation for static data. The hook can be installed by using the npm install use-copy command.

Steps to Run the Function

The copy to clipboard reacts application can be run on a local environment using the npm start command. The npm start command will run the react-scripts start command which renders the react application on the browser.

After running the command, react will open the browser automatically. If it doesn't navigate to http://localhost:3000/ on the browser to see the website.

Final Output

The image shows the final output of react copy to clipboard function.

final output of react copy to clipboard function

Conclusion

  • React Copy to Clipboard functionality is used to copy data to the clipboard without using commands or controls.
  • We can use different third-party libraries or the javascript Clipboard API to copy data.
  • The libraries can be installed using the npm or yarn package manager.
  • The CopyToClipboard component copies the data present in the text value.
  • The data passed as a parameter to the copy() function of the useCopyToClipboard hook is copied.
  • In the useCopy hook, the data passed on the useCopy() hook is copied using the copy() function.