When displaying referral links, API keys, etc. it is useful to allow customers to click a button to copy the contained content.
import {
TextField,
Button,
Tooltip,
Visibility,
toast,
} from '@krakentech/coral';
import { useCallback, useEffect, useState } from 'react';
import { IconCopy, IconSuccessOutlined } from '@krakentech/icons';
const [linkCopied, setLinkCopied] = useState(false);
const link = 'octo.ps';
const copyToClipboard = useCallback(async (code: string) => {
try {
await window.navigator.clipboard.writeText(code);
setLinkCopied(true);
} catch (error) {
handleCopyFailure(error);
}
}, []);
const copyFailureMessage = 'dashboard.referrals.copyFailure';
const handleCopyFailure = (error: any) => {
toast(error.message, {
type: 'error',
toastId: copyFailureMessage,
});
};
useEffect(() => {
const timeout = setTimeout(() => {
setLinkCopied(false);
}, 2000);
return () => clearTimeout(timeout);
}, [linkCopied]);
<TextField
label="Referral Link"
value={link}
endIcon={
<Button variant="text" onClick={() => copyToClipboard(link)}>
{linkCopied ? (
<Tooltip placement="top" title="Copied!">
<IconSuccessOutlined size={24} />
</Tooltip>
) : (
<>
<IconCopy size={24} />
<Visibility hidden>Copy</Visibility>
</>
)}
</Button>
}
/>