How to copy text to clipboard in React example
This tutorial covers copy text to the clipboard using below two methods
- navigator.clipboard
- react-copy-to-clipboard npm
navigator object
in javascript provides browser capabilities, It has a clipboard API interface for accessing the system clipboard, and It provides cut, copies, and pastes functionalities of the native operating system. However, a clipboard is a short content buffer that exists across multiple pages or requests.
Copy text to clipboard using navigator
System clipboard in react can be accessed using Navigator.clipboard API. The writeText
method provides writing content to the clipboard.
Navigator support all major browsers🔗.
In this example,
- There is a textbox and button on a page and a button click to copy the text to the clipboard
- user enters the text into the textbox, event handler
onChange
fires, and stores this into react state. - On clicking the button, the onClick event fires, and its event handler executes
- Inside handler, Copy textbox value into clipboard using
writeText
method
import React, { Component } from "react";
class CopyToClipboard extends Component {
constructor(props) {
super(props);
this.state = {
result: "",
name: "",
};
// this.updateInput = this.updateInput.bind(this);
// this.handleSubmit = this.handleSubmit.bind(this);
}
handleChange = (event) => {
this.setState({ name: event.target.value });
};
handleSubmit(event) {
console.log("kiran", event.target.value);
try {
navigator.clipboard.writeText(event.target.value);
this.setState({
result: "Copied To clipboard",
});
} catch (err) {
this.setState({
result: "Copy Failed",
});
}
}
render() {
return (
<div>
<input type="text" onChange={this.updateInput} />
<button onClick={this.handleSubmit}>Copy text</button>
<div>status : {this.state.result}</div>
</div>
);
}
}
export default CopyToClipboard;
The same functionality can be achieved with the popular react-copy-to-clipboard npm
library
react-copy-to-clipboard example
First, Install the react-copy-to-clipboard
library to the existing react application with the below npm command.
npm install --save react react-copy-to-clipboard
CopyToClipboard
is a wrapper or container for a button that contains text attribute with content and result callback with onCopy attribute. It has a button as a child element.
Call-back events function to bind the typed text.
Complete example:
import React, { Component } from "react";
class CopyToClipboard extends Component {
constructor(props) {
super(props);
this.state = {
result: "",
name: "",
};
}
handleChange = (event) => {
this.setState({ name: event.target.value });
};
copyStatus() {
this.setState({
result: "Copied",
});
}
render() {
return (
<div>
<input type="text" onChange={this.updateInput} />
<CopyToClipboard text={this.state.name} onCopy={this.copyStatus}>
<button>Copy</button>
</CopyToClipboard>
<div>status : {this.state.result}</div>
</div>
);
}
}
export default CopyToClipboard;