I'm working with the react-pdf
library and attempting to add a custom onClick
event handler to the PDFDownloadLink component. The goal is to trigger a custom download action when the user clicks to download the PDF. However, when I add the onClick handler, I encounter an error message that says, "Check Internet Connection." Strangely, if I remove the onClick event, the file downloads correctly.
Here's the relevant code snippet:
<div key={uuid()} className={classes.__wrapper}>
<PDFDownloadLink
onClick={onDownload} // Problematic onClick
style={{ textDecoration: "none", color: "black" }}
fileName={`${sku}.pdf`}
document={<PDFDocument pages={pages} />}
>
{({ loading, blob }) =>
loading ? <PDFLoader /> : <FileDownloadLink blob={blob} sku={sku} />
}
</PDFDownloadLink>
</div>
The onDownload
function is meant to handle the download logic, and it works fine when not used in the onClick event. I suspect that there might be an issue with how the onClick event is being handled.
Can someone help me understand why adding the onClick event is causing this error, and how I can resolve it to trigger the custom download action successfully?
So I digged a bit deeper in the source code, as I was actually having the same issue. I mean I needed to perform some action when I get the downloaded file. The onClick also sends event: MouseEvent and instance: ReactPDF.BlobProviderParams
so you can have a function like that
const generatePdfSuccess = async (
event: MouseEvent,
instance: ReactPDF.BlobProviderParams
) => {
if (instance.loading || !instance.url) {
return;
}
downloadURI(instance.url, `filename.pdf`);
closeModal();
// or anything else you want to happen after download
};
and because onClick would prevent the regular download from the library you can use function like the below to download this file with your code
function downloadURI(uri: string, name: string) {
const link = document.createElement("a");
link.href = uri;
link.download = name;
link.click();
}
hope it helps