VOOZH about

URL: https://www.geeksforgeeks.org/reactjs/how-to-copy-text-to-the-clipboard-in-react-js/

⇱ How To Copy Text To The Clipboard In ReactJS? - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

How To Copy Text To The Clipboard In ReactJS?

Last Updated : 23 Jul, 2025

In ReactJS, you can copy text to the clipboard using two methods. One way is to use the copy-to-clipboard package, which provides a simple copy() function to handle the task. Alternatively, you can use the browser's built-in window.navigator.clipboard.writeText() method, which copies text to the clipboard directly by calling navigator.clipboard.writeText('your text'). Both methods make it easy to copy text efficiently in your React applications.

Prerequisites

Below are 2 approaches mentioned to copy text to the clipboard using React:

Steps To Copy Text to the Clipboard

Step 1: Create React Project using the following command.

npm create-react-app react-copy-text
cd react-copy-text

Step 2: Install there required dependencies.

npm i --save styled-components copy-to-clipboard

Project Structure

👁 Image
Folder structure

Dependencies

dependencies": {
 "@testing-library/jest-dom": "^5.17.0",
 "@testing-library/react": "^13.4.0",
 "@testing-library/user-event": "^13.5.0",
 "copy-to-clipboard": "^3.3.3",
 "react": "^18.2.0",
 "react-dom": "^18.2.0",
 "react-scripts": "5.0.1",
 "styled-components": "^6.0.9",
 "web-vitals": "^2.1.4"
}

Approach 1: Using copy-to-clipboard

To copy text to the clipboard in React we will use the NPM packagecopy-to-clipboard which enables the copying of any text from the input box or value stored in any component.

Example: Created to input box and link the first input box value to a useState hook instance. Pass this value in teh copy method that trrigers when the given button is clicked.


To start the application run the following command.

npm start

Output: Now open your browser and go to http://localhost:3000/, you will see the following output:

👁 Image
Copy Text using Using copy-to-clipboard

Approach 2: Using window.navigator.clipbord method

We will be using the navigator property from window global object to make the text copy to clipboard.

Example: This approach includes the use of window.navigator.clipboard.writeText method to write the data. The value in the textbox will be copied to clipboard when the button is clicked.


Output: Now open your browser and go to http://localhost:3000/, you will see the following output:

👁 Image
Copy Text To The Clipboard In ReactJS
Comment
Article Tags: