How to Create and Export Text Files from a React Frontend

Although it may be surprising, it’s possible to create and download files from a React frontend. What reasons could you have for doing this? If all the data you want to export is already available to you in the frontend, you could avoid a request to the backend. It could also be that you don’t want to update an existing endpoint to handle a specific case. Regardless of why you may want to, here’s how to export data directly from a React frontend.

1. Stringify the data.

First, we’ll need to get the data we want to export and stringify it. This could be the response from a backend request or just information from a form that the user filled out. For our example, we’ll use an object containing user data provided to our export function. This step would be a good opportunity to make any changes to the formatting of the data using JSON.stringify()’s parameters.


const fileData = JSON.stringify(userInfo);

2. Blobify the data<./h2>

Once a string, our file data can be turned into a blob and a URL to that blob object can be created. In our case, we set MiME type to “text/plain” since it is a simple JSON file.


const blob = new Blob([fileData], { type: "text/plain" });
const url = URL.createObjectURL(blob);

3. Create a link in the DOM and click it.

Now that we have a URL for our blob data, we can link to it. To do this, we’ll inject a link into the DOM. Once we create the element, we’ll update properties on it to reflect the file to download.


const link = document.createElement("a");
link.download = "user-info.json";
link.href = url;

Finally, we can go ahead and interact with the link we just created. This should immediately download the file.


link.click();

4. Put it all together.

If we followed the steps above, we should end up with the following function:


type UserInfo = {
  name: string;
  email: string;
}

function exportUserInfo(userInfo: UserInfo) {
  const fileData = JSON.stringify(userInfo);
  const blob = new Blob([fileData], { type: "text/plain" });
  const url = URL.createObjectURL(blob);
  const link = document.createElement("a");
  link.download = "user-info.json";
  link.href = url;
  link.click();
}

Using this function, you can easily wire up a button to create and export simple text files from your React frontend without needing to make a request or any changes to the backend.