Skip to content

Instantly share code, notes, and snippets.

@lebbe
Created September 5, 2023 16:03
Show Gist options
  • Save lebbe/83679f5ab9e8029fdac5df53ae9fb8b6 to your computer and use it in GitHub Desktop.
Save lebbe/83679f5ab9e8029fdac5df53ae9fb8b6 to your computer and use it in GitHub Desktop.
React hook for turning a string into a downloadable txt-file
/**
* This hook returns an URL you can use in the href-attribute of an anchor element,
* so the provided string will be downloaded as a txt-file.
*/
function useTxtBlobifier(document: string) {
const [loading, setLoading] = useState(true);
const [url, setUrl] = useState('');
// Remove the unused url instance if/when the document
// changes, or when component unmounts.
useEffect(() => {
return () => {
if (url) {
URL.revokeObjectURL(url);
}
};
}, [url]);
const instance = { loading, url };
useEffect(
function () {
if (document && typeof document === 'string') {
// Fix typesetting issues if document is opened in the browser
// (typically new tab, instead of downloading)
const BOM = new Uint8Array([0xef, 0xbb, 0xbf]);
const blob = new Blob([BOM, document], {
type: 'text/plain',
});
setUrl(URL.createObjectURL(blob));
setLoading(false);
} else {
setLoading(true);
}
},
[document]
);
return { url, loading };
}
// TODO: I could release a component into npm that resembles react-pdf, only for txt-files instead.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment