Copy text to clipboard
11 сентября 2025 г.
To copy text to the clipboard, use navigator.clipboard.writeText("some text").
JavaScript
1navigator?.clipboard2 .writeText(text)3 .then(() => {4 //some action5 })6 .catch((err) => console.error(`Error copying text:`, err));
Below is an example of a copy button component for React:
JavaScript
1import { useState } from "react";23const CopyButton = ({ text }) => {4 const [copied, setCopied] = useState(false);56 const copy = () => {7 navigator?.clipboard8 .writeText(text)9 .then(() => {10 setCopied(true);11 setTimeout(() => setCopied(false), 2000);12 })13 .catch((err) => console.error(`Error copying text:`, err));14 };1516 return (17 <button18 onClick={copy}19 >20 {copied ? (21 <span>Copied</span>22 ) : (23 <span>Copy</span>24 )}25 </button>26 );27};2829export default CopyButton;