Skip to content

Instantly share code, notes, and snippets.

@d88naimi
Created August 24, 2021 22:34
Show Gist options
  • Save d88naimi/5974ba306e5756704b6f73e07302054c to your computer and use it in GitHub Desktop.
Save d88naimi/5974ba306e5756704b6f73e07302054c to your computer and use it in GitHub Desktop.
import React, { useState, useEffect } from "react";
import cx from "classnames";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { faClipboard, faCheck } from "@fortawesome/free-solid-svg-icons";
import { Button } from "../Button";
import styles from "./CopyButton.less";
export const CopyButton = (props) => {
const [copied, setCopied] = useState(false);
function fallback(text) {
if (window.clipboardData && window.clipboardData.setData) {
// IE specific code path to prevent textarea being shown while dialog is visible.
return window.clipboardData.setData("Text", text);
} else if (
document.queryCommandSupported &&
document.queryCommandSupported("copy")
) {
const textarea = document.createElement("textarea");
textarea.innerText = text;
document.body.appendChild(textarea);
textarea.select();
try {
setCopied(true);
document.execCommand("copy");
} catch (err) {
console.err(err);
return false;
} finally {
document.body.removeChild(textarea);
}
}
}
const copyValue = () => {
if (navigator.clipboard) {
navigator.clipboard.writeText(props.value);
setCopied(true);
} else {
fallback(props.value);
}
};
useEffect(() => {
let iconTimer = setTimeout(() => {
setCopied(false);
}, 1000);
return () => {
clearTimeout(iconTimer);
};
}, [copied]);
return (
<Button className={cx(styles.CopyButton, props.className)} onClick={copyValue} kind="outlined" size="small">
{copied ? (
<FontAwesomeIcon
className={cx(styles.Icon, styles.CheckIcon)}
icon={faCheck}
/>
) : (
<FontAwesomeIcon className={styles.Icon} icon={faClipboard} />
)}
{props.children ? props.children : props.value}
</Button>
);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment