I have a copy icon that should take the value and put it into the clipboard. I'm using the an Iframe, so the clipboard api is working on firefox but not on chrome, which awful, but the workaround with execCommand is doing it's job. My is issue is that when you click on the copy icon, the tooltip should change from 'Copy' to 'Copied' and should stay like that until then user is focusing that element, but instead, after the click the tooltip disappear. I noticed that the state is actually changing, and if i remove the document.body.removeChild(elem), the tooltip behavior is good, but of course is not copying the text.
import React, { useState } from "react";
import CopyIcon from "@atlaskit/icon/glyph/copy";
import Tooltip from "@atlaskit/tooltip";
import Button from "@atlaskit/button";
export default function CopyClipboard(props) {
/**
* position - position of the tooltip
* value - value to copy
* size - size of the icon
* label - Text used to describe what the icon is in context
* style - style of the component
*/
const [tooltip, setTooltip] = useState("Copy to Clipboard");
function copyFun() {
navigator.clipboard
.writeText(props.value)
.catch((error) => {
const elem = document.createElement('textarea');
elem.value = props.value;
document.body.appendChild(elem);//this is the line creating the error
elem.focus();
elem.select()
document.execCommand('copy');
document.body.removeChild(elem);
console.error(error)
})
.finally(() => {
setTooltip("Copied to clipboard");
})
}
return (
<Tooltip
content={tooltip}
position={props.position}
onHide={() => {setTooltip("Copy to Clipboard")}}
>
{(tooltipProps) => (
<Button spacing="none" style={props.style} appearance="subtle-link" className="copy-to-clipboard" {...tooltipProps} onClick={copyFun}>
<CopyIcon size={props.size} label={props.label}/>
</Button>
)}
</Tooltip>
);
}