useClipboard
React hook to copy to the clipboard.
Add the hook via the CLI:
bash
npx @novajslabs/cli add useClipboard
bash
npx @novajslabs/cli add useClipboard
bash
pnpm dlx @novajslabs/cli add useClipboard
Or copy and paste the code into your project:
ts
import { useState } from "react";
export const useClipboard = () => {
const [copiedText, setCopiedText] = useState<string | null>("");
const copyToClipboard = (value: string) => {
return new Promise<string>((resolve, reject) => {
try {
if (navigator?.clipboard?.writeText) {
navigator.clipboard
.writeText(value)
.then(() => {
setCopiedText(value);
resolve(value);
})
.catch((e) => {
setCopiedText(null);
reject(e);
});
} else {
setCopiedText(null);
throw new Error("Clipboard not supported");
}
} catch (e) {
reject(e);
}
});
};
return { copiedText, copyToClipboard };
};
js
import { useState } from "react";
export const useClipboard = () => {
const [copiedText, setCopiedText] = useState("");
const copyToClipboard = (value) => {
return new Promise((resolve, reject) => {
try {
if (navigator?.clipboard?.writeText) {
navigator.clipboard
.writeText(value)
.then(() => {
setCopiedText(value);
resolve(value);
})
.catch((e) => {
setCopiedText(null);
reject(e);
});
} else {
setCopiedText(null);
throw new Error("Clipboard not supported");
}
} catch (e) {
reject(e);
}
});
};
return { copiedText, copyToClipboard };
};
Requirements
React 16.8 or higher
Return values
copiedText
Type: string | null
The text currently copied to the clipboard. If null
, it means that the copyToClipboard
function encountered an error.
copyToClipboard
Type: function
Copy a text to the clipboard. This function accepts the text to copy and returns a promise.
Example
tsx
import { useClipboard } from "./hooks/useClipboard";
import { useRef } from "react";
const App = () => {
const { copiedText, copyToClipboard } = useClipboard();
const inputRef = useRef<HTMLInputElement>(null);
const handleClick = () => {
copyToClipboard(inputRef.current?.value || "")
.then(() => alert("Copied!"))
.catch(() => alert("Failed!"));
};
return (
<div>
<input type="text" ref={inputRef} />
<button onClick={handleClick}>Copy input text</button>
</div>
);
};
export default App;
Use cases
Here are some use cases where this React hook is useful:
- Enabling users to copy text to the clipboard in a web-based note-taking app
- Implementing a "Share" button in a web app to copy a link to the clipboard
- Facilitating easy copying of coupon codes in an e-commerce website
- Allowing users to quickly copy error messages for reporting in a bug tracking tool
- Implementing a "Copy to Clipboard" feature for sharing code snippets in a developer community platform