Welcome folks today in this blog post we will be downloading raw text and csv files
as attachment in browser using react-download-link
library in browser using javascript. All the full source code of the application is shown below.
Get Started
In order to get started you need to make a new react.js
project using the below command
npx create-react-app sampleapp
cd sampleapp
And after that you will see the below directory
structure of the react.js app as shown below
And now we need to edit the App.js
file and copy paste the following code
App.js
1 2 3 4 5 6 7 8 9 10 11 12 13 |
import DownloadLink from "react-download-link"; export default function App() { return ( <div className="App"> <DownloadLink label="Save" filename="myfile.txt" exportFile={() => "My cached data"} /> </div> ); } |
As you can see we are importing the react-download-link
library at the top and then we are using the DownloadLink
element where we are passing the label
and filename
and then we have the callback
function where we providing the data
which will be present inside the text
file.
Downloading CSV File
Now we will be providing the .csv
extension inside the filename and then we will be providing the csv
data inside the export
method as shown below
1 2 3 4 5 6 7 8 9 10 11 12 13 |
import DownloadLink from "react-download-link"; export default function App() { return ( <div className="App"> <DownloadLink label="Save" filename="myfile.csv" exportFile={() => "Name,Age,Couuntry\nJohn,25,India"} /> </div> ); } |