DEV Community

Krishna Sharma
Krishna Sharma

Posted on

Create a File Uploader with Progress Bar in React.js

Uploading Files in any web application is very common these days, so providing a good user experience to the users during large file uploads is nice to have. So in this post, we will learn how to create a simple React.js component in which you can upload a file and show how much it is uploaded in percentage (%) so the user can patiently wait for it to complete and doesn't worry about how much he's to wait.

So here I'm assuming that you're using axios library for making API calls, as this is the most popular library making api calls with lot of features. Within this library, when we hit an api endpoint, we may provide addition parameters by using them we can show users the upload progress bar. Let me create an example component:

import React, { useState } from "react"
import axios from "axios"

const UploadFile = () => {
    const [state, setState] = useState({ percentage: 0, isUploading: false }) // can have more properties like fileName, size etc.

    const onChange = async ({ target: { files } }) => {
        const file = files[0]

        if (!file) return

        const formData = new FormData()

        formData.append('file', file)

        setState(prevState => ({...prevState, isUploading: true }))

        await axios.post('http://any-url-to.upload', formData, {
            onUploadProgress({ loaded, total }) {
                if (!total) return

                const percentage = Math.floor((loaded / total) * 100)

                setState((prevState) => ({
                    ...prevState,
                    percentage: percentage,
                    isUploading: percentage !== 100,
                }))
            },
        })
    }

    return (
        <div>
            <input type="file" onChange={onChange} />
            {state.isUploading ? (
                <div style={{ background: "orange" }}>
                    <div>
                        <h2>{`Uploading File: ${state.percentage} %`}</h2>
                    </div>
                    <div className="progress-bar" style={{ background: "white", height: 30 }}>
                        <div style={{ width: `${state.percentage}%`, background: "green" }} />
                    </div>
                </div>
            ) : (
                <div>
                    {state.percentage === 100 ? <h1>
                        Your file is uploaded!
                    </h1> : <h1>Please select a File to upload</h1>}
                </div>
            )}
        </div>
    )
}

export default UploadFile;
Enter fullscreen mode Exit fullscreen mode

As we can see, showing the Upload progress in React is pretty simple, all we need to do is manage state for the File or Files and when we got to upload, we may provide a custom callback function to the axios config's onUploadProgress method, and then update the state accordingly to show the user the expected behavior for the File being uploaded with progress bar, which can be customized with CSS.

Top comments (0)