How to create a progress bar for file downloads in a React.js app



Image not found!!


Creating a progress bar for file downloads in a React.js app involves utilizing the browser's built-in XHR (XMLHttpRequest) or Fetch API to download files and tracking the progress of the download. Here's a basic implementation using XHR:

  1. Create a component for the progress bar:

    Create a new component named FileDownloadProgressBar.js:

    jsx
    import React, { useState } from 'react'; const FileDownloadProgressBar = ({ fileUrl }) => { const [progress, setProgress] = useState(0); const handleDownload = () => { const xhr = new XMLHttpRequest(); xhr.onprogress = (event) => { if (event.lengthComputable) { const percentComplete = (event.loaded / event.total) * 100; setProgress(percentComplete); } }; xhr.onload = () => { setProgress(100); }; xhr.open('GET', fileUrl, true); xhr.responseType = 'blob'; xhr.send(); }; return ( <div> <button onClick={handleDownload}>Download File</button> <div className="progress"> <div className="progress-bar" style={{ width: `${progress}%` }}>{`${progress.toFixed(2)}%`}</div> </div> </div> ); }; export default FileDownloadProgressBar;
  2. Style the progress bar:

    You can style the progress bar using CSS. Here's a simple example:

    css
    .progress { width: 100%; background-color: #f0f0f0; } .progress-bar { height: 20px; background-color: #007bff; text-align: center; line-height: 20px; color: white; }
  3. Use the component:

    Import and use the FileDownloadProgressBar component in your application:

    jsx
    import React from 'react'; import FileDownloadProgressBar from './FileDownloadProgressBar'; const App = () => { return ( <div> <h1>File Download Progress</h1> <FileDownloadProgressBar fileUrl="https://example.com/file.pdf" /> </div> ); }; export default App;

This basic implementation will display a progress bar while downloading a file. However, you may want to add error handling, styling enhancements, and more advanced features depending on your specific requirements. Additionally, consider using libraries like Axios for more robust HTTP requests handling in React applications.