From ebf65fdc6bb0c03b6e935e22d3e795df8d14966a Mon Sep 17 00:00:00 2001 From: Jerel Miller Date: Thu, 11 Jun 2020 12:45:56 -0700 Subject: [PATCH] feat: Create a useClipboard hook. Move copy clipboard code into a util function --- src/hooks/useClipboard.js | 26 ++++++++++++++++++++++++++ src/utils/copyToClipboard.js | 11 +++++++++++ 2 files changed, 37 insertions(+) create mode 100644 src/hooks/useClipboard.js create mode 100644 src/utils/copyToClipboard.js 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;