Explain Codes LogoExplain Codes Logo

In reactJS, how to copy text to clipboard?

javascript
prompt-engineering
functions
callbacks
Alex KataevbyAlex KataevยทJan 8, 2025
โšกTLDR

Seize the moment to copy text to clipboard in React with minimal effort using navigator.clipboard.writeText():

const copyTextToClipboard = async (text) => { try { await navigator.clipboard.writeText(text); console.log('Text swiftly copied to clipboard! ๐Ÿ’จ'); } catch (err) { console.error('Houston, we have a problem ๐Ÿš€:', err); } };

Summon this superpower via:

<button onClick={() => copyTextToClipboard('Your precious text here')}>Copy</button>

Fast and efficient: just click the button and voila, you've copied!

Retrieves text from older scrolls (Handling older browsers)

Older browsers are like ancient scrolls, they need a translator. Use document.execCommand or window.clipboardData.setData as a scroll interpreter. ๐Ÿ“œโ†”๏ธ๐Ÿ’ฌ

const copyTextWithFallback = (text) => { const inputArea = document.createElement('textarea'); inputArea.value = text; document.body.appendChild(inputArea); inputArea.select(); try { const success = document.execCommand('copy'); const msg = success ? 'successful' : 'unsuccessful'; console.log(`Fallback: Copying operation was ${msg}! ๐Ÿ€`); } catch (err) { console.error('Fallback: Oops! Something went wrong here ๐Ÿ˜ž', err); } document.body.removeChild(inputArea); };

Scrutinize, analyze! (Detecting copy support)

Wars are won with proper reconnaissance. Tailor your attack with document.queryCommandSupported('copy').

const isCopySupported = () => document.queryCommandSupported('copy');

Casting a spell with react-copy-to-clipboard

Getting your hands dirty isn't your style? Let react-copy-to-clipboard do it for you!

npm install --save react-copy-to-clipboard

Just give the command and watch the text vanish from your React component:

import { CopyToClipboard } from 'react-copy-to-clipboard'; const YourComponent = () => { const [text, setText] = useState('Copy this text, please'); const [isCopied, setIsCopied] = useState(false); const onCopyText = () => { setIsCopied(true); setTimeout(() => setIsCopied(false), 1500); }; return ( <> <input value={text} onChange={({target}) => setText(target.value)} /> <CopyToClipboard text={text} onCopy={onCopyText}> <button>Copy</button> </CopyToClipboard> {isCopied ? <span style={{color: 'green'}}>Copied! Look at you go! ๐Ÿš€</span> : null} </> ); };

Deep dive into different scenarios (Versatile usage patterns)

Association with Input Elements

Work smarter not harder. Attach a copy function with an input element to get more done in less time.

const CopyInputText = ({ value }) => { const inputRef = useRef(); const copyText = () => { inputRef.current.select(); copyTextToClipboard(value); }; return ( <> <input ref={inputRef} value={value} onChange={() => {}} /> <button onClick={copyText}>Copy like a magician! ๐Ÿ‡</button> </> ); };

Button with a sense of humor (Stateful Button with Feedback)

Include a self-aware button that not only copies on click but also cracks a joke for you:

const CopyButtonWithFeedback = ({ textToCopy }) => { const [copied, setCopied] = useState(false); const handleCopyClick = async () => { await copyTextToClipboard(textToCopy); setCopied(true); setTimeout(() => setCopied(false), 2000); }; return ( <button onClick={handleCopyClick}> {copied ? 'Copied! Easy peasy lemon squeezy ๐Ÿ‹' : 'Copy'} </button> ); };

Autopilot mode (Programmatically without User Trigger)

When actions become repetitive, go full autopilot:

useEffect(() => { const copyAutomatically = async () => { await copyTextToClipboard('Text to be copied automatically'); // Additional logic after text copied... }; copyAutomatically(); }, []);