Categories
React Answers

How to download file on button click with React and JavaScript?

Spread the love

To download file on button click with React and JavaScript, we create a link

And then we can create a hidden link that has the blob’s object URL set as the href attribute and click on the link programmatically to download it.

For instance, we write:

import React from "react";

export default function App() {
  const downloadFile = () => {
    const element = document.createElement("a");
    element.href = url;
    element.download = "filename";
    document.body.appendChild(element);
    element.click();
  };

  return (
    <div>
      <button onClick={downloadFile}>Download txt</button>
    </div>
  );
}

to define the downloadFile function to put the 'hello world' string in a blob and download that as a text file.

In the function, we create an a element with document.createElement.

Next, we set element.href to the fil’s URL.

And we set the file name of the downloaded file by setting the element.download property.

Next, we call document.body.appendChild with the link element to attach it to the body.

Finally, we call element.click to click on the hidden link to download the file.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published.