Components
Copy To Clipboard Button
텍스트를 클립보드에 복사할 수 있는 버튼 컴포넌트입니다.
console.log('Hello, World!')"use client";import { CopyToClipboardButton } from "@/registry/default/components/copy-to-clipboard-button";import { Input } from "@/components/ui/input";export function CopyToClipboardButtonExample() { const text = "console.log('Hello, World!')"; return ( <div className="flex flex-col items-center gap-4"> <div className="flex items-center gap-4"> <code className="relative rounded bg-muted px-[0.3rem] py-[0.2rem] font-mono text-sm font-semibold"> {text} </code> <CopyToClipboardButton text={text} /> </div> <Input /> </div> );}설치
pnpm
pnpm dlx shadcn@latest add @chaesunbak/copy-to-clipboard-buttonnpm
npx shadcn@latest add @chaesunbak/copy-to-clipboard-button다음 코드를 프로젝트에 복사/붙여넣기 하세요.
import { useState } from "react";import { Copy, Check } from "lucide-react";import { useCopyToClipboard, useTimeout } from "usehooks-ts";import { Button } from "@/components/ui/button";export function CopyToClipboardButton({ text, className, onSuccess, onError,}: { text: string; className?: string; onSuccess?: () => void; onError?: () => void;}) { const [_, copy] = useCopyToClipboard(); const [isCopied, setIsCopied] = useState(false); // 복사 성공 시 2초 후에 상태를 초기화합니다. // isCopied가 true일 때만 타이머가 작동하며, false이면 타이머가 해제됩니다. useTimeout(() => setIsCopied(false), isCopied ? 2000 : null); const handleCopy = async () => { const success = await copy(text); if (success) { setIsCopied(true); onSuccess?.(); } else { onError?.(); } }; return ( <Button variant="outline" size="sm" onClick={handleCopy} className={className} > {isCopied ? ( <> <Check className="mr-1 size-4" /> 복사됨 </> ) : ( <> <Copy className="mr-1 size-4" /> 복사 </> )} </Button> );}관련 의존성을 추가하세요.
사용법
import { CopyToClipboardButton } from "@/components/copy-to-clipboard-button";<CopyToClipboardButton text="복사할 텍스트" />인터페이스
CopyToClipboardButton
| 속성 | 타입 | 기본값 | 설명 |
|---|---|---|---|
text | string | - | 복사할 텍스트입니다. |
className | string | undefined | 추가적인 스타일 클래스입니다. |
onSuccess | () => void | undefined | 복사 성공 시 호출됩니다. |
onError | () => void | undefined | 복사 실패 시 호출됩니다. |