How to download a string as .txt file in React?

Sometimes, we want to download a string as .txt file in React.

In this article, we’ll look at how to download a string as .txt file in React.

How to download a string as .txt file in React?

To download a string as .txt file in React, we can convert the string into a blob.

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 downloadTxtFile = () => {
    const element = document.createElement("a");
    const file = new Blob(["hello world"], {
      type: "text/plain"
    });
    element.href = URL.createObjectURL(file);
    element.download = "myFile.txt";
    document.body.appendChild(element);
    element.click();
  };

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

to define the downloadTxtFile 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 define a blob with 'hello world' as its content with the Blob constructor.

We set the type property to 'text/plain' to make the downloaded file a text file.

Next, we set element.href to the object URL version of the blob that we create with URL.createObjectURL.

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.

Conclusion

To download a string as .txt file in React, we can convert the string into a blob.

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.