Copy to clipboard
Today we talk about creating own hook called UseCopyToClipboard in ReactJS. It's a hook that allows you to copy text to clipboard. So let's start:
For what?
I found this very useful when you have a code section and you want to copy it to clipboard. It's usually a small button in right corner of code section.
Coding
import { useState } from "react";
const useCopyToClipboard = () => {
const [copiedText, setCopiedText] = useState(null);
const copy = async (text) => {
if (!navigator || !navigator.clipboard) {
console.warn("Clipboard not supported");
return false;
}
try {
await navigator.clipboard.writeText(text);
setCopiedText(text);
return true;
} catch (error) {
console.warn("Copy failed", error);
setCopiedText(null);
return false;
}
};
return [copiedText, copy];
};
export default useCopyToClipboard;
Note: This hook is not supported in IE11 and below. Because of navigator.clipboard missing. If you want to support IE11, you can use clipboard.js.
Usage
import { useCopyToClipboard } from ".../.../...";
export default function Component() {
const [value, copy] = useCopyToClipboard();
return (
<>
<div>
<button onClick={() => copy("Hello")}>Hello</button>
<button onClick={() => copy("React")}>React</button>
<button onClick={() => copy("JavaScript")}>JavaScript</button>
</div>
<p>Copied value: {value ? value : "Nothing is copied yet!"}</p>
</>
);
}
Here we use copy function to copy text to clipboard. And value is the text that is copied.
Conclusion
Using the useCopyToClipboard hook improving the user experience to make "fast-copy". I hope you will find it useful too. Give it a try in your own projects and see how it works for you!
March 6, 2023
Go back