Created
April 15, 2022 22:54
-
-
Save aeksco/3d3fe47a8945d423814db306fa009b03 to your computer and use it in GitHub Desktop.
Simple CopyToClipboard React Component + Hook
This file contains 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 * as React from "react"; | |
// // // // | |
/** | |
* Exposes navigator.writeText via React hook with optional callback | |
*/ | |
export function useCopyToClipboard( | |
callback?: () => void | |
): [(textToCopy: string) => void] { | |
// Defines copyToClipboard function passed to props.children | |
function copyToClipboard(textToCopy: string) { | |
navigator.clipboard.writeText(textToCopy); | |
if (callback) callback(); | |
} | |
return [copyToClipboard]; | |
} | |
/** | |
* Exposes navigator.writeText via render props with optional callback | |
*/ | |
export function CopyToClipboard(props: { | |
onCopy?: () => void; | |
children: (childProps: { | |
copyToClipboard: (textToCopy: string) => void; | |
}) => React.ReactNode; | |
}) { | |
const [copyToClipboard] = useCopyToClipboard(props.onCopy); | |
return ( | |
<React.Fragment>{props.children({ copyToClipboard })}</React.Fragment> | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment