Skip to content

Commit

Permalink
feat: Create a useClipboard hook. Move copy clipboard code into a uti…
Browse files Browse the repository at this point in the history
…l function
  • Loading branch information
jerelmiller committed Jun 11, 2020
1 parent 52bdb61 commit ebf65fd
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 0 deletions.
26 changes: 26 additions & 0 deletions src/hooks/useClipboard.js
Original file line number Diff line number Diff line change
@@ -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;
11 changes: 11 additions & 0 deletions src/utils/copyToClipboard.js
Original file line number Diff line number Diff line change
@@ -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;

0 comments on commit ebf65fd

Please sign in to comment.