Last active
February 19, 2025 18:08
-
-
Save viclafouch/cceefaa8895bd6b6a684e3aa4a5aad14 to your computer and use it in GitHub Desktop.
A custom React Hook for writing and reading from the modern clipboard API
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
// hooks/use-clipboard-api.js | |
import { useState, useCallback } from 'react' | |
function useClipboardApi() { | |
const [content, setContent] = useState(null) | |
const askPermission = useCallback(async queryName => { | |
try { | |
const permissionStatus = await navigator.permissions.query(queryName) | |
return permissionStatus.state === 'granted' | |
} catch (error) { | |
// Browser compatibility / Security error (ONLY HTTPS) ... | |
return false | |
} | |
}, []) | |
const copy = useCallback( | |
async blob => { | |
const hasWritePermission = await askPermission({ name: 'clipboard-write' }) | |
if (hasWritePermission) { | |
const content = [new ClipboardItem({ [blob.type]: blob })] | |
await navigator.clipboard.write(content).then(read) | |
} | |
}, | |
[askPermission, read] | |
) | |
const read = useCallback(async () => { | |
const hasReadPermission = await askPermission({ name: 'clipboard-read' }) | |
if (hasReadPermission) { | |
const content = await navigator.clipboard.read() | |
setContent(content) | |
} | |
}, [askPermission]) | |
useEffect(() => { | |
read() | |
}, [read]) | |
return { content, copy } | |
} | |
export default useClipboardApi |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment