aboutsummaryrefslogtreecommitdiffstats
path: root/src/components/share-url-button.tsx
diff options
context:
space:
mode:
authorSebastien Castiel <sebastien@castiel.me>2023-12-13 12:55:31 -0500
committerSebastien Castiel <sebastien@castiel.me>2023-12-13 13:01:59 -0500
commit9e2834abc323e9b46803b764b0d04393d437a7cc (patch)
treec14d3fa189af3cc8f58c5fd0b437157360e13e6e /src/components/share-url-button.tsx
parent6bd99d9a346d8af23911b73de011ea951c889661 (diff)
Add share button
Diffstat (limited to 'src/components/share-url-button.tsx')
-rw-r--r--src/components/share-url-button.tsx44
1 files changed, 44 insertions, 0 deletions
diff --git a/src/components/share-url-button.tsx b/src/components/share-url-button.tsx
new file mode 100644
index 0000000..d31aa78
--- /dev/null
+++ b/src/components/share-url-button.tsx
@@ -0,0 +1,44 @@
+'use client'
+
+import { Button } from '@/components/ui/button'
+import { Share } from 'lucide-react'
+import { useEffect, useState } from 'react'
+
+interface Props {
+ text: string
+ url: string
+}
+
+export function ShareUrlButton({ url, text }: Props) {
+ const canShare = useCanShare(url, text)
+ if (!canShare) return null
+
+ return (
+ <Button
+ size="icon"
+ variant="secondary"
+ type="button"
+ onClick={() => {
+ if (navigator.share) {
+ navigator.share({ text, url })
+ } else {
+ console.log('Sharing is not available', { text, url })
+ }
+ }}
+ >
+ <Share className="w-4 h-4" />
+ </Button>
+ )
+}
+
+function useCanShare(url: string, text: string) {
+ const [canShare, setCanShare] = useState<boolean | null>(null)
+
+ useEffect(() => {
+ setCanShare(
+ navigator.share !== undefined && navigator.canShare({ url, text }),
+ )
+ }, [text, url])
+
+ return canShare
+}