useCopy
The useCopy hook is a common hook provided by the Hartan library. This hook uses the native web Clipboard API internally to provide the copy functionality on the text provided by user.
This hook is a public hook and available for the users to use.
Code
import { useState } from "react"
export default function useCopy(textToCopy) {
const [isCopied, setIsCopied] = useState(false);
async function copyTextToClipboard(text) {
if ('clipboard' in navigator) {
return await navigator.clipboard.writeText(text);
} else {
return document.execCommand('copy', true, text);
}
}
const handleCopyClick = () => {
copyTextToClipboard(textToCopy)
.then(() => {
setIsCopied(true);
setTimeout(() => {
setIsCopied(false);
}, 1500);
})
.catch((err) => {
console.log(err);
});
}
return [isCopied, handleCopyClick]
}Explanation
As you can see above it uses the useState hook of the React and the native Clipboard API internally.
It accepts a single parameter, the text to be copied to clipboard, which is provided by the user.
It returns two things:
isCopied: a state value to tell that text is copied.handleCopyClick: the function which contains the copy logic.
Usage
Last updated