Skip to content

Instantly share code, notes, and snippets.

@joepuzzo
Last active November 5, 2020 18:19
Show Gist options
  • Save joepuzzo/c69f67941c8ecb7c14fe728da9afbb27 to your computer and use it in GitHub Desktop.
Save joepuzzo/c69f67941c8ecb7c14fe728da9afbb27 to your computer and use it in GitHub Desktop.
import React, { useState, useRef } from 'react';
const useClipboard = () => {
const [copySuccess, setCopySuccess] = useState('Copy');
const textAreaRef = useRef(null);
function copyToClipboard(e: any) {
// @ts-ignore
const copyText = textAreaRef.current.textContent;
const textArea = document.createElement('textarea');
textArea.textContent = copyText;
document.body.append(textArea);
textArea.select();
document.execCommand('copy');
setCopySuccess('Copied!');
document.body.removeChild(textArea);
setTimeout(() => {
setCopySuccess('Copy');
}, 5000);
}
return { textAreaRef, copySuccess, copyToClipboard };
};
interface CodeBlockProps {
children: any;
}
export const CodeBlock = (props: CodeBlockProps) => {
const { children } = props;
const { textAreaRef, copyToClipboard, copySuccess } = useClipboard();
return (
<pre className="code-block">
<code ref={textAreaRef}>{children}</code>
<button onClick={copyToClipboard}>
{/* @ts-ignore */}
<i className="tds-icon tds-icon--small tds-icon-bag" title="copy to clipboard"></i>
{copySuccess}
</button>
</pre>
);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment