Copy text to the Clipboard in ReactJS
Many developers are facing the issue while implementing the copy to clipboard functionality. So today I am going to show you how to copy text to clipboard.
Here we will use npm plugin to implement copy to clipboard functionality. Couple of ways are also available to do it. But it’s the simplest way to achieve the functionality.
Checkout more articles on React JS:
Way to Copy text to the Clipboard in ReactJS
1. Install copy-to-clipboard plugin
To install the copy to clipboard package, You have to run the following command. By the use of that we will download the copy-to-clipboard package.
1 | npm i --save copy-to-clipboard |
2. Import package and use it on button click
To implement it, You have to import package in page via below command and run the copy
command to copy the text to clipboard.
1 2 3 | import copy from 'copy-to-clipboard'; copy('Text'); |
Here we will create small demo where we add one button and input field on page. By clicking on the button we will copy the text from the input field to clipboard.
You have to create the startup react application for that you may use the create-react-app. Checkout the article below for more information.
How to create react applicationAdd input field and button to manage the functionality. Your code should look like below.
App.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 | import React, { Component } from 'react'; import copy from "copy-to-clipboard"; class App extends Component { constructor() { super(); this.state = { textToCopy: "Copy to Clipboard Demo!", btnText: "Copy to Clipboard" }; this.handleInputChange = this.handleInputChange.bind(this); this.handleCopy = this.handleCopy.bind(this); } handleInputChange(e) { this.setState({ textToCopy: e.target.value, btnText: "Copy to Clipboard" }); } handleCopy() { copy(this.state.textToCopy); this.setState({ btnText: "Copied!" }); } render() { const { textToCopy, btnText } = this.state; return ( <div> <h4>Clue Mediator - Copy to Clipboard</h4> <textarea value={textToCopy} onChange={this.handleInputChange} /> <br /> <br /> <button onClick={this.handleCopy} disabled={btnText === "Copied!"}> {btnText} </button> </div> ); } } export default App; |