Skip to content

Instantly share code, notes, and snippets.

@tlux
Created December 17, 2024 20:26
Show Gist options
  • Save tlux/bf1478b39607d4e617afe1c8ccfcdcda to your computer and use it in GitHub Desktop.
Save tlux/bf1478b39607d4e617afe1c8ccfcdcda to your computer and use it in GitHub Desktop.
React hook to trigger a download of a Blob/File or MediaSource
import { useCallback } from 'react';
export function useDownload() {
return useCallback((obj: Blob | MediaSource, filename: string) => {
const url = URL.createObjectURL(obj);
const link = document.createElement('a');
link.href = url;
if (filename) {
link.download = filename;
}
link.click();
URL.revokeObjectURL(url);
}, []);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment