Copy to Clipboard

A hook that wraps navigator.clipboard and enhances it. You can also provide timeout to show small animation after copy button clicked.

copy to clipboard demo

use-clipboard.tsx

tsx
1"use client";
2
3import { useState } from "react";
4
5interface UseCopyToClipboardProps {
6  timeout?: number;
7}
8
9export function useCopyToClipboard({
10  timeout = 2000,
11}: UseCopyToClipboardProps) {
12  const [isCopied, setIsCopied] = useState<boolean>(false);
13
14  const copyToClipboard = (value: string) => {
15    if (typeof window === "undefined" || !navigator.clipboard?.writeText) {
16      return;
17    }
18
19    if (!value) {
20      return;
21    }
22
23    navigator.clipboard.writeText(value).then(() => {
24      setIsCopied(true);
25
26      setTimeout(() => {
27        setIsCopied(false);
28      }, timeout);
29    });
30  };
31
32  return { isCopied, copyToClipboard };
33}

Usage

tsx
1export default function MessageItem() {
2  const { isCopied, copyToClipboard } = useCopyToClipboard({ timeout: 2000 });
3
4  return (
5    <Button
6      onClick={copyToClipboard("some text")}
7    >
8      {isCopied ? <Icons.Check className="text-success" /> : <Icons.Copy />}
9    </Button>;
10  );
11}

Loved this post?

Comments

Interested in
working
with me?

Let's Connect

Stay in touch 👇

© 2021 - 2025 itsrakesh. v2.