React Answers

How to add React file download with JavaScript?

Spread the love

To add React file download with 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; = "filename";

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

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 property.

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

Finally, we call 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. Required fields are marked *