Skip to content

Instantly share code, notes, and snippets.

@aeksco
Created April 15, 2022 22:54
Show Gist options
  • Save aeksco/3d3fe47a8945d423814db306fa009b03 to your computer and use it in GitHub Desktop.
Save aeksco/3d3fe47a8945d423814db306fa009b03 to your computer and use it in GitHub Desktop.
Simple CopyToClipboard React Component + Hook
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