Skip to content
Source
Sign inSign up
TanStack/router
Open History to see the last commit

useClipboard.js

26 lines719 Bytes

1import * as React from 'react';
2import copy from 'copy-to-clipboard';
3/**
4 * React hook to copy content to clipboard
5 *
6 * @param text the text or value to copy
7 * @param timeout delay (in ms) to switch back to initial state once copied.
8 */
9​
10export function useClipboard(text, timeout = 1500) {
11 const [hasCopied, setHasCopied] = React.useState(false);
12 const onCopy = React.useCallback(() => {
13 const didCopy = copy(text);
14 setHasCopied(didCopy);
15 }, [text]); // @ts-ignore
16​
17 React.useEffect(() => {
18 if (hasCopied) {
19 const id = setTimeout(() => {
20 setHasCopied(false);
21 }, timeout);
22 return () => clearTimeout(id);
23 }
24 }, [timeout, hasCopied]);
25 return [hasCopied, onCopy];