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.
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.
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 application
Add input field and button to manage the functionality. Your code should look like below.
App.js
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;
3. Output
Output - Copy text to the Clipboard in ReactJS - Clue Mediator
You may also like: Date Range Picker in React