How to Create Copy to Clipboard in React: Simple Guide
In React, you can create a copy to clipboard feature by using the
navigator.clipboard.writeText() method inside an event handler. Combine this with React hooks like useState to provide user feedback after copying text.Syntax
The main method to copy text to clipboard is navigator.clipboard.writeText(text). It returns a promise that resolves when the text is copied. Use this inside a React event handler like onClick. Optionally, use useState to track copy success and show messages.
javascript
const copyToClipboard = async (text) => { try { await navigator.clipboard.writeText(text); console.log('Text copied to clipboard'); } catch (err) { console.error('Failed to copy text: ', err); } };
Example
This example shows a React functional component with a button that copies a fixed text to the clipboard. It also shows a message when the copy is successful.
javascript
import React, { useState } from 'react'; export default function CopyExample() { const [copied, setCopied] = useState(false); const textToCopy = 'Hello, React Clipboard!'; const handleCopy = async () => { try { await navigator.clipboard.writeText(textToCopy); setCopied(true); setTimeout(() => setCopied(false), 2000); } catch (err) { console.error('Failed to copy:', err); } }; return ( <div> <p>{textToCopy}</p> <button onClick={handleCopy} aria-label="Copy text to clipboard"> Copy Text </button> {copied && <span role="alert" style={{ marginLeft: '10px', color: 'green' }}>Copied!</span>} </div> ); }
Output
Displays text 'Hello, React Clipboard!' with a 'Copy Text' button. Clicking the button copies the text and shows 'Copied!' message briefly.
Common Pitfalls
- Not handling promise rejection from
navigator.clipboard.writeText()can cause silent failures. - Trying to use clipboard API on insecure origins (non-HTTPS) will not work.
- For older browsers, the Clipboard API may not be supported; fallback methods are needed.
- Not providing user feedback can confuse users if they don't know if copy succeeded.
javascript
/* Wrong: ignoring errors and no feedback */ const copyWrong = (text) => { navigator.clipboard.writeText(text); // no await or catch }; /* Right: with async/await and error handling */ const copyRight = async (text) => { try { await navigator.clipboard.writeText(text); alert('Copied!'); } catch { alert('Copy failed'); } };
Quick Reference
Remember these key points when implementing copy to clipboard in React:
- Use
navigator.clipboard.writeText()inside async functions. - Handle errors with
try/catch. - Provide user feedback after copying.
- Ensure your site uses HTTPS for Clipboard API support.
- Use React hooks like
useStateto manage UI state.
Key Takeaways
Use the Clipboard API's navigator.clipboard.writeText() inside async React event handlers.
Always handle promise rejections to catch copy failures.
Provide clear user feedback after copying text.
Clipboard API requires HTTPS for security reasons.
React hooks like useState help manage copy status and UI updates.