![]() |
VOOZH | about |
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.
Below are 2 approaches mentioned to copy text to the clipboard using React:
Table of Content
npm create-react-app react-copy-text
cd react-copy-textnpm i --save styled-components copy-to-clipboarddependencies": {
"@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"
}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 startOutput: Now open your browser and go to http://localhost:3000/, you will see the following output:
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: