Skip to content

Instantly share code, notes, and snippets.

@shuntksh
Created November 12, 2023 04:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shuntksh/722a44cefd64b94c9a343b203ab8bc06 to your computer and use it in GitHub Desktop.
Save shuntksh/722a44cefd64b94c9a343b203ab8bc06 to your computer and use it in GitHub Desktop.
React Component to Copy Value to Clipboard
import { useCallback, useState } from 'react';
import { CheckIcon, CopyIcon } from 'lucide-react';
type Timeout = number | undefined;
type ClipboardProps = {
value: string;
onError?: (err: Error) => void;
} & React.HTMLAttributes<HTMLButtonElement>;
const CopyButton = ({ value, onError, onClick, ...rest }: ClipboardProps) => {
const [buttonLabel, setButtonLabel] = useState(<CopyIcon className="text-muted-foreground h-4 w-4" />);
let cancelToken: Timeout = 0;
// Function to copy text to clipboard
const copyToClipboard = useCallback(
(ev: React.MouseEvent<HTMLButtonElement>) => {
document.clearTimeout(cancelToken);
navigator.clipboard
.writeText(value)
.then(() => {
setButtonLabel(<CheckIcon className="text-muted-foreground h-4 w-4" />);
cancelToken = document.setTimeout(() => {
setButtonLabel(<CopyIcon className="text-muted-foreground h-4 w-4" />);
}, 500);
if (onClick) {
onClick(ev);
}
})
.catch((err) => {
console.error(err);
if (onError) {
onError(err);
}
});
},
[value],
);
return (
<button onClick={copyToClipboard} {...rest}>
{buttonLabel}
</button>
);
};
export default CopyButton;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment