Created
March 19, 2023 06:57
-
-
Save Sachin-chaurasiya/56154e66a68f077bc1d858ca4d3c92da to your computer and use it in GitHub Desktop.
Custom hook for copy to clipboard functionality
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { useCallback, useEffect, useState } from 'react'; | |
/** | |
* React hook to copy text to clipboard | |
* @param value the text to copy | |
* @param timeout delay (in ms) to switch back to initial state once copied. | |
* @param callBack execute when content is copied to clipboard | |
*/ | |
export const useClipboard = ( | |
value: string, | |
timeout = 1500, | |
callBack?: () => void | |
) => { | |
// local state | |
const [hasCopied, setHasCopied] = useState(false); | |
const [valueState, setValueState] = useState(value); | |
// handlers | |
const handleCopy = useCallback(async () => { | |
try { | |
await navigator.clipboard.writeText(valueState); | |
setHasCopied(true); | |
callBack && callBack(); | |
} catch (error) { | |
setHasCopied(false); | |
} | |
}, [valueState]); | |
// side effects | |
useEffect(() => setValueState(value), [value]); | |
useEffect(() => { | |
let timeoutId: number | null = null; | |
if (hasCopied) { | |
timeoutId = Number( | |
setTimeout(() => { | |
setHasCopied(false); | |
}, timeout) | |
); | |
} | |
return () => { | |
if (timeoutId) { | |
clearTimeout(timeoutId); | |
} | |
}; | |
}, [timeout, hasCopied]); | |
return { | |
onCopyToClipBoard: handleCopy, | |
hasCopied, | |
}; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment