fbpx

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.

Install with :

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))}
    />
Other React Tutorials