react copy text code example
Example 1: how to copy to clipboard in react js
<button
onClick={() => navigator.clipboard.writeText('Copy this text to clipboard')}
>
Copy
</button>
Example 2: copy text to clipboard reactjs
import React, { useRef, useState } from 'react';
export default function CopyExample() {
const [copySuccess, setCopySuccess] = useState('');
const textAreaRef = useRef(null);
function copyToClipboard(e) {
textAreaRef.current.select();
document.execCommand('copy');
e.target.focus();
setCopySuccess('Copied!');
};
return (
<div>
{
document.queryCommandSupported('copy') &&
<div>
<button onClick={copyToClipboard}>Copy</button>
{copySuccess}
</div>
}
<form>
<textarea
ref={textAreaRef}
value='Some text to copy'
/>
</form>
</div>
);
}
Example 3: copy text to clipboard javascript react
onClick={() => {navigator.clipboard.writeText(this.state.textToCopy)}}
Example 4: copy text using react js
import React, { Component } from "react"
export default class YourComponent extends Component {
constructor(props) {
super(props)
this.state = {
copySuccess: false
}
}
copyCodeToClipboard = () => {
const el = this.textArea
el.select()
document.execCommand("copy")
this.setState({copySuccess: true})
}
render() {
return (
<div>
<div>
<textarea
ref={(textarea) => this.textArea = textarea}
value="Example copy for the textarea."
/>
</div>
<div>
<button onClick={() => this.copyCodeToClipboard()}>
Copy to Clipboard
</button>
{
this.state.copySuccess ?
<div style={{"color": "green"}}>
Success!
</div> : null
}
</div>
</div>
)
}
}