How to create a copy to clipboard コピーボタンの作り方
Button that copies text to clipboard and shows feedback. クリックでテキストをコピーし、フィードバックを表示するボタン。
ライブデモ Live Demo
概要・用途・特徴Overview, Usage & Features
何ができるかWhat it does
Button that copies text to clipboard and shows feedback.
クリックでテキストをコピーし、フィードバックを表示するボタン。
どこで使うかWhere to use
user engagement, data entry, content management, settings panel
コードスニペット、APIキー表示、共有URL、メールアドレス表示
特徴Key features
One-click copy to clipboard using the Clipboard API. Visual feedback (icon change + color) confirms successful copy. Auto-resets after a configurable delay. Falls back to document.execCommand for older browsers.
Clipboard APIによるワンクリックコピー。視覚的フィードバック(アイコン変更+色)でコピー成功を確認。設定可能な遅延後に自動リセット。古いブラウザのdocument.execCommandフォールバック。
調整可能パラメータ Adjustable Parameters
| Parameter | Default | Description |
|---|---|---|
--success-bg | — | Success background color |
--feedback-duration | — | Feedback display duration |
実装コード Implementation Code
<button class="copy-btn" onclick="copy('some text')">Copy</button>
<script>
async function copy(text) {
try {
await navigator.clipboard.writeText(text);
const btn = document.querySelector('.copy-btn');
btn.classList.add('copied');
setTimeout(() => btn.classList.remove('copied'), 2000);
} catch (err) {
console.error('Failed to copy', err);
}
}
</script>
/* react/I-009.css */
/* I-009: React styles */
.copy-btn {
background: #f5f7ff;
border: none;
border-radius: 6px;
padding: 8px 12px;
cursor: pointer;
font-size: 14px;
font-weight: 600;
color: #5c6184;
transition: all 0.2s;
position: relative;
}
.copy-btn:hover {
background: #e0e4f0;
color: #1d2242;
}
.copy-btn::after {
content: 'Copied!';
position: absolute;
top: -30px;
left: 50%;
transform: translateX(-50%) translateY(10px);
background: #1d2242;
color: #fff;
padding: 4px 8px;
border-radius: 4px;
font-size: 12px;
opacity: 0;
pointer-events: none;
transition: all 0.2s;
}
.copy-btn.copied::after {
opacity: 1;
transform: translateX(-50%) translateY(0);
}
.copy-btn.copied {
background: #dafbe1;
color: #1a7f37;
}
import { useState } from 'react';
import './I-009.css';
export default function CopyButton({ text }) {
const [copied, setCopied] = useState(false);
const handleCopy = async () => {
try {
await navigator.clipboard.writeText(text);
setCopied(true);
setTimeout(() => setCopied(false), 2000);
} catch (err) {
console.error(err);
}
};
return (
<button className={`copy-btn ${copied ? 'copied' : ''}`} onClick={handleCopy}>
{copied ? 'Copied!' : 'Copy'}
</button>
);
}
/* I-009: React styles */
.copy-btn {
background: #f5f7ff;
border: none;
border-radius: 6px;
padding: 8px 12px;
cursor: pointer;
font-size: 14px;
font-weight: 600;
color: #5c6184;
transition: all 0.2s;
position: relative;
}
.copy-btn:hover {
background: #e0e4f0;
color: #1d2242;
}
.copy-btn::after {
content: 'Copied!';
position: absolute;
top: -30px;
left: 50%;
transform: translateX(-50%) translateY(10px);
background: #1d2242;
color: #fff;
padding: 4px 8px;
border-radius: 4px;
font-size: 12px;
opacity: 0;
pointer-events: none;
transition: all 0.2s;
}
.copy-btn.copied::after {
opacity: 1;
transform: translateX(-50%) translateY(0);
}
.copy-btn.copied {
background: #dafbe1;
color: #1a7f37;
}
仕組みとカスタマイズHow It Works & Customization
仕組みHow it works
The copy button calls navigator.clipboard.writeText() with the target text (from a data attribute or sibling element). On success, a CSS class swaps the button icon to a checkmark and changes its color. A setTimeout resets the state after the feedback duration.
コピーボタンがnavigator.clipboard.writeText()をターゲットテキスト(data属性または兄弟要素から)で呼び出します。成功時、CSSクラスがボタンアイコンをチェックマークに交換し色を変更。setTimeoutがフィードバック時間後に状態をリセット。
カスタマイズ方法Customization
Change the feedback icon from ✓ to "Copied!" text for more explicit confirmation. Adjust the reset delay (default 2s) to be shorter for snappy UIs. Add a toast notification alongside the button feedback for visibility at a distance.
フィードバックアイコンを✓から"Copied!"テキストに変えてより明確な確認に。スナッピーなUIのためリセット遅延(デフォルト2s)を短くする。距離のある場所での視認性のためにボタンフィードバックと並行してトースト通知を追加。
注意点Caveats
navigator.clipboard requires a secure context (HTTPS or localhost). Always handle the rejected promise gracefully — show an error message or fall back to selecting the text for manual copy. Test on iOS Safari where clipboard permissions may differ.
navigator.clipboardはセキュアコンテキスト(HTTPSまたはlocalhost)が必要です。拒否されたプロミスを常にグレースフルに処理してください — エラーメッセージを表示するか手動コピーのためにテキストを選択するフォールバックに。クリップボード権限が異なる可能性があるiOS Safariでテストしてください。
よくある質問 Frequently Asked Questions
How to customize the copy to clipboard? Copy to Clipboardをカスタマイズするには?
Modify the CSS custom properties and class styles defined in the code section. Key adjustable values include colors, sizes, durations, and spacing. See the Adjustable Parameters section for specific variables.
コードセクションで定義されているCSSカスタムプロパティとクラススタイルを変更してください。色、サイズ、時間、間隔が主な調整可能値です。具体的な変数は調整可能パラメータセクションを参照してください。
How to use the copy to clipboard in React? ReactでCopy to Clipboardを使うには?
Import the provided React component and its CSS file. The component accepts props for customization. Check the React code section for the full implementation and available props.
提供されているReactコンポーネントとCSSファイルをインポートしてください。コンポーネントのpropsでカスタマイズできます。完全な実装と利用可能なpropsはReactコードセクションを参照してください。
What are the performance implications of copy to clipboard? Copy to Clipboardのパフォーマンスへの影響は?
This implementation uses CSS transforms and opacity for animations, which are GPU-accelerated. It's lightweight and doesn't cause layout thrashing. Consider using prefers-reduced-motion for accessibility.
この実装はCSSのtransformとopacityを使用しており、GPUアクセラレーションされます。軽量でレイアウトスラッシングを引き起こしません。アクセシビリティのためにprefers-reduced-motionの使用を検討してください。
AIへの指示テンプレート AI Prompt Template
以下をAIに貼り付けると実装を依頼できます。 Paste the following into your AI assistant to request implementation.