Welcome folks today in this blog post we will be using the react-progress library to show youtube progressbar
animation to download the file 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
app using the below command as shown below
npx create-react-app sampleapp
cd sampleapp
And after that you need to install the below library
using the below command as shown below
npm i react-progress
And after that you will see the below directory
structure of the react.js app as shown below
Showing Simple Youtube Progressbar Animation
Now we can modify the App.js
file and copy paste the following code
App.js
1 2 3 4 5 6 7 8 9 10 |
import Progress from "react-progress"; export default function App() { return ( <div> <Progress style={{display:"block"}} percent={50} height={1} color="rainbow" /> </div> ); } |
As you can see we are importing the react-progress
at the top and then we are showing the youtube
progressbar animation widget and then we are passing various options
such as the percent
and the color
of the animation. And also we can control the height
of the animation as well.
Downloading File With Progressbar
Now guys we will be downloading file using fetch
api with progressbar animation as shown below.
App.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 |
import { useState } from "react"; import Progress from "react-progress"; export default function App() { const [percent,setPercent] = useState(0) const [progressbar,setProgressbar] = useState("none") const handleClick = () => { setProgressbar("block") let progress = 0; const intervalId = setInterval(async () => { progress += 25; if (progress > 100) { clearInterval(intervalId); const response = await fetch("https://images.unsplash.com/photo-1676481945425-621e73a056ce?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxlZGl0b3JpYWwtZmVlZHwyfHx8ZW58MHx8fHw%3D&auto=format&fit=crop&w=500&q=60", { method: "GET", headers: { "Content-Type": "application/json", } }); const blob = await response.blob(); const url = URL.createObjectURL(blob); const link = document.createElement("a"); link.href = url; link.download = "sample.jpg"; link.click(); setPercent(0) setProgressbar("none") } else { setPercent(progress); } }, 500); } return ( <div> <Progress style={{display:progressbar}} percent={percent} height={1} /> <button onClick={handleClick}>Download</button> </div> ); } |
As you can see we are having the progress
and progressbar
hooks variable for tracking the percent of the progress
downloaded file and also toggling the visibility
of the progressbar. And then we have the button
in which we have binded the onClick
where we are executing the handleDownload()
method and inside it we are using the fetch
api to download the file as an attachment using the blob
property.