Last active
November 5, 2020 18:19
-
-
Save joepuzzo/c69f67941c8ecb7c14fe728da9afbb27 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 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