Skip to content

Instantly share code, notes, and snippets.

@DaveBitter
Created February 2, 2022 11:44
Show Gist options
  • Save DaveBitter/acfc8b6bb18f9208a9c7035b45c1a59d to your computer and use it in GitHub Desktop.
Save DaveBitter/acfc8b6bb18f9208a9c7035b45c1a59d to your computer and use it in GitHub Desktop.
// Libs
import { useState } from "react";
// Utils
// Type
export type UseShareType = {
type: 'copy' | 'share';
content: string;
}
// Component
const useShare = ({ type, content }: UseShareType) => {
const [usedShareType, setUsedShareType] = useState<UseShareType['type']>(type);
const [showCopiedFeedback, setShowCopiedFeedback] = useState(false);
const triggerShare = () => {
const triggerCopyToClipboard = () => {
setUsedShareType('copy');
const placeholder = document.createElement('input');
document.body.appendChild(placeholder);
placeholder.setAttribute('value', content);
placeholder.select();
document.execCommand('copy');
document.body.removeChild(placeholder);
setShowCopiedFeedback(true)
setTimeout(() => {
setShowCopiedFeedback(false);
}, 2000)
};
const triggerNativeShare = () => {
if (!window.navigator['share']) {
setUsedShareType('copy');
triggerCopyToClipboard()
} else {
setUsedShareType('share');
window.navigator['share']({
url: content
});
}
};
switch (type) {
case 'share':
triggerNativeShare();
default:
triggerCopyToClipboard();
break;
}
}
return { usedShareType, triggerShare, showCopiedFeedback }
};
// Props
useShare.defaultProps = {
type: 'copy'
};
export default useShare;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment