To create a progress bar for document uploads (such as PDF files) in a React.js app, you can use the native XMLHttpRequest object or modern fetch API to upload the document to the server. You'll then track the progress of the upload using the progress
event and update the progress bar accordingly. Here's how you can achieve this:
javascriptimport React, { useState } from 'react';
const DocumentUpload = () => {
const [file, setFile] = useState(null);
const [progress, setProgress] = useState(0);
const handleFileChange = (e) => {
setFile(e.target.files[0]);
};
const handleUpload = () => {
const formData = new FormData();
formData.append('document', file);
const xhr = new XMLHttpRequest();
xhr.open('POST', '/upload', true);
xhr.upload.addEventListener('progress', (event) => {
if (event.lengthComputable) {
const percentage = (event.loaded / event.total) * 100;
setProgress(Math.round(percentage));
}
});
xhr.onreadystatechange = () => {
if (xhr.readyState === XMLHttpRequest.DONE) {
// Upload complete
// Handle response from server if needed
}
};
xhr.send(formData);
};
return (
<div>
<input type="file" onChange={handleFileChange} />
<button onClick={handleUpload}>Upload</button>
{progress > 0 && <progress value={progress} max="100" />}
</div>
);
};
export default DocumentUpload;
Style the Progress Bar:
Style the progress bar using CSS to make it visually appealing. You can customize the appearance of the progress bar using CSS properties like width
, height
, background-color
, and border-radius
.
Use the DocumentUpload Component:
Finally, use the DocumentUpload
component in your application wherever you want to allow users to upload documents.
javascriptimport React from 'react';
import DocumentUpload from './DocumentUpload';
const App = () => {
return (
<div>
<h1>Document Upload App</h1>
<DocumentUpload />
</div>
);
};
export default App;
With these steps, you'll have a progress bar that tracks the upload progress of document files in your React.js app. Users can select a document file, and the progress bar will update as the file is uploaded to the server.