useShare
The useShare hook wraps the Web Share API, which opens the native share sheet on phones, tablets, and some desktop browsers. Closing the sheet without sharing is not treated as an error.
Usage
Installation
import { useShare } from "hookstorm";
Parameters
This hook does not take any parameters.
Return Values
- isSupported —
trueif the browser can share. - isSharing —
truewhile the share sheet is open. - error — The last error, or
null. - share(data) — Opens the share sheet for a
ShareDataobject (title,text,url,files). Returns a promise that resolves totrueif the share was completed.
Example Usage
import { ReactElement } from "react";
import { useShare } from "hookstorm";
export default function ShareButton(): ReactElement {
const { isSupported, isSharing, error, share } = useShare();
if (!isSupported) return <p>Sharing is not supported on this device.</p>;
return (
<div>
<button
disabled={isSharing}
onClick={() => share({ title: "Hookstorm", url: window.location.href })}
>
Share this page
</button>
{error && <p>Could not share: {error.message}</p>}
</div>
);
}
Notes
- Browsers only allow sharing from a user gesture such as a click, so call
sharefrom an event handler. - Render a fallback (for example a copy-link button using
useCopyToClipboard) whenisSupportedisfalse. - Requires a secure context (
https://orlocalhost).