diff --git a/src/hooks/useClipboard.js b/src/hooks/useClipboard.js new file mode 100644 index 000000000..307c276bc --- /dev/null +++ b/src/hooks/useClipboard.js @@ -0,0 +1,26 @@ +import { useEffect, useState, useCallback } from 'react'; +import copyToClipboard from '../utils/copyToClipboard'; + +const useClipboard = ({ duration = 1000 } = {}) => { + const [copied, setCopied] = useState(false); + const copy = useCallback((text) => { + copyToClipboard(text); + setCopied(true); + }, []); + + useEffect(() => { + if (copied && duration) { + const id = setTimeout(() => { + setCopied(false); + }, duration); + + return () => { + clearTimeout(id); + }; + } + }, [copied, duration]); + + return [copied, copy]; +}; + +export default useClipboard; diff --git a/src/utils/copyToClipboard.js b/src/utils/copyToClipboard.js new file mode 100644 index 000000000..7404dbee4 --- /dev/null +++ b/src/utils/copyToClipboard.js @@ -0,0 +1,11 @@ +const copyToClipboard = (text) => { + const textArea = document.createElement('textarea'); + + textArea.value = text; + document.body.appendChild(textArea); + textArea.select(); + document.execCommand('copy'); + document.body.removeChild(textArea); +}; + +export default copyToClipboard;