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

.map is not a function

map() can only be used with Arrays. So, if you are getting error .map is not a function, you are probably using it on either the objects or other variables…
View Post

How to use React?

This article will help you to know how to use React JS in web applications. React js creates static websites with optimized performance and speed. Step 1: Install create-react-app npm…
View Post