How to download file in react JS – React Download Link

In this post we are going to have a look at one of the rarest and simple thing in react React Download Link .

React download link is simple component to download data from a client side cache. Example for Client side cache are flux, redux.

Either we can download data from client side cache or we can fetch data from provided URL.

In todays world with SPA dominating the web file download operations are becoming popular and downloading files from server is a common use case . In this article we will show you how you can download the data using component based approach .We are basically focusing on react and if you able to do it using react you can do same thing in other SPA use cases . let’s have a look how we can do it . Have a look if you want to do it in a server side language using spring .

Install with React-Download Link:

npm install --save react-download-link
npm i react-download-link

Include:

 import DownloadLink from "react-download-link";

react-download-link component mainly have following props.

label : The name/label on browser page.

filename : downloading file name.

exportFile : function to get file content to be downloaded.

The component will default to an anchor tag, but the tagName prop will accept a string of any other HTML tag you prefer, such as ‘button’.

Examples :

  1. React download link for client side cache data
<DownloadLink
    label="Download"
    filename="fileName.txt"
    exportFile={() => "Client side cache data here…"}
/>

2. Download link for client side cache data with Promises

<DownloadLink
    label="Download with Promise"
    filename="fileName.txt"
    exportFile={() => Promise.resolve("cached data here …")}
/>

3. Download link for data from URL with Promises

Function to Fetch data from URL

 getDataFromURL = (url) => new Promise((resolve, reject) => {
        setTimeout(() => {
            fetch(url)
                .then(response => response.text())
                .then(data => {
                    resolve(data)
                });
        });
    }, 2000);

DownloadLink component calling Fetch function

<DownloadLink
          label=”Download”
          filename=”filename.txt”
          exportFile={() => Promise.resolve(this. getDataFromURL (url))}
    />

We have seen how to use React to create a Download feature .

Other React Tutorials

Leave a Comment