React download files on button click


React download files on button click using temporary anchor tag. It is helpful in case when you are getting binary data from a link. This binary file could be pdf, image, excel, word document, text or anything else. Fetch the link using Axios or javascript fetch api and download file with this code –

  method: "get",
  url: "downloadSamplePDF.php",
  responseType: "arraybuffer"
  .then((response) => {
    var link = document.createElement("a");
    link.href = window.URL.createObjectURL(
      new Blob([], { type: "application/octet-stream" })
    ); = "name_of_file_with_extension";

    setTimeout(function () {
    }, 200);
  .catch((error) => {});

    Tweet this to help others

You might have to take care of CORS errors if you are dealing with cross origin requests. The downloadSamplePDF.php file will return the binary data. Also provide the name of file with extension in

Sign Up for Our Newsletters

Get only the best articles delivered to your mail

You May Also Like

React convert JSON to CSV

React convert JSON to CSV using JSONToCSVConvertor function. Suppose you have a table (GUI react table tool) and you want to export it into excel, then this function will come…
View Post