-
Notifications
You must be signed in to change notification settings - Fork 0
useClipboard
Saurav-TB-Pandey edited this page Aug 8, 2026
·
2 revisions
Reads and writes text to the user's clipboard, managing a temporary "copied" state. Great for "Copy to Clipboard" buttons.
The simplest possible implementation, using the default 2-second reset timeout.
import { useClipboard } from 'react-hook-lab';
function BasicCopy() {
const { copy, copied } = useClipboard();
return (
<button onClick={() => copy("Hello World!")}>
{copied ? "Copied!" : "Copy Text"}
</button>
);
}Handling potential clipboard errors (e.g. when the page is not served over HTTPS or lacks focus).
import { useClipboard } from 'react-hook-lab';
function ErrorHandlingCopy({ textToCopy }) {
const { copy, copied, error } = useClipboard(1500); // Reset state after 1.5 seconds
const handleCopy = async () => {
const success = await copy(textToCopy);
if (!success) {
console.warn("Fallback required for copying");
}
};
return (
<div>
<button onClick={handleCopy}>
{copied ? "✅ Copied!" : "📋 Copy Code"}
</button>
{error && <span style={{color: 'red'}}> {error.message}</span>}
</div>
);
}An exhaustive example utilizing all properties, including dynamic timeouts based on state.
import { useClipboard } from 'react-hook-lab';
import { useState } from 'react';
function AdvancedCopy() {
const [timeout, setTimeoutVal] = useState(3000);
const { copy, copied, error } = useClipboard(timeout);
return (
<div>
<input
type="number"
value={timeout}
onChange={e => setTimeoutVal(Number(e.target.value))}
step={100}
/>
<label> Reset Timeout (ms)</label>
<br/><br/>
<button onClick={() => copy(`Copied with a ${timeout}ms reset!`)} disabled={copied}>
{copied ? `Waiting ${timeout}ms...` : "Copy dynamic text"}
</button>
{error && <p>Failed: {error.message}</p>}
</div>
);
}-
timeout- Type:
number - Default:
2000 - Description: The duration in milliseconds before the
copiedstate automatically resets tofalseafter a successful copy operation.
- Type:
Returns an object containing:
-
copied(boolean):trueif the text was successfully copied and the timeout hasn't elapsed.falseotherwise. -
error(Error | null): The caught Error if the clipboard operation fails (e.g., Clipboard API not supported or permission denied). -
copy((text: string) => Promise<boolean>): The asynchronous function to execute the copy operation. Returns a promise resolving totrueon success, orfalseon failure.
Built with ❤️ by Saurav-TB-Pandey. | Report an Issue | NPM