React File Uploader Frontend Loaders - Multiple values in single state - Single function for multiple uploads

    By: Thad Mertz
    6 months ago

    In today's web development landscape, user experience is paramount. Users expect fast and responsive web applications, especially when uploading files. In this tutorial, we'll show you how to create a file upload progress bar in a React application using the Chakra UI library and the React Top Loading Bar component. This user-friendly interface will keep your users informed about the progress of their file uploads. Let's dive in!


    Setting Up Your React App


    To get started, make sure you have Node.js and npm (Node Package Manager) installed on your system. If you don't, you can download them from the official website.


    Once you have Node.js and npm ready, follow these steps:


    1. Create a new React app:


    npx create-react-app file-upload-progress-bar
    


    2. Change into the project directory:


    cd file-upload-progress-bar
    


    3. Install the necessary packages:


    npm install @chakra-ui/react react-top-loading-bar
    


    Creating the File Upload Progress Bar


    Now that we have our React app set up and the required packages installed, let's start building the file upload progress bar.


    Writing the Code


    1. Replace the contents of the `src/index.js` file with the following code:


    import React from "react";
    import ReactDOM from "react-dom";
    import App from "./App";
    import { ChakraProvider } from "@chakra-ui/react";
    
    const root = document.getElementById("root");
    ReactDOM.render(
     <ChakraProvider>
      <App />
     </ChakraProvider>,
     root
    );
    


    2. Create a new file called `src/App.js` and add the following code:


    import React from "react";
    import Main from "./components/Main";
    
    function App() {
     return <Main />;
    }
    
    export default App;
    


    3. Create a new folder called `src/components` and inside it, create a file named `Main.jsx`. Add the following code:


    import React, { useState, useEffect } from "react";
    import {
     Container,
     Table,
     Tbody,
     Td,
     Tfoot,
     CircularProgress,
     CircularProgressLabel,
     Th,
     Thead,
     Tr,
    } from "@chakra-ui/react";
    import LoadingBar from "react-top-loading-bar";
    
    export default function Main() {
     // State for tracking file upload progress
     const [progress, setProgress] = useState({
      fileOne: 0,
      fileTwo: 0,
      fileThree: 0,
      fileFour: 0,
      fileFive: 0,
     });
    
     // State for storing uploaded file content
     const [fileContent, setFileContent] = useState({
      fileOne: 0,
      fileTwo: 0,
      fileThree: 0,
      fileFour: 0,
      fileFive: 0,
     });
    
     // State for the main progress bar
     const [progressMain, setProgressMain] = useState();
    
     // Function to prepare a file for upload
     const prepareFileForUpload = (event, fileType) => {
      setProgressMain(0);
      setProgress({
       ...progress,
       [fileType]: 0,
      });
      const file = event.target.files[0];
      let stopAfterSeconds = file.size.toString().charAt(0);
    
      if (file) {
       const interval = setInterval(() => {
        if (stopAfterSeconds) {
         let progressNow = 100 / stopAfterSeconds;
    
         setProgress({
          ...progress,
          [fileType]: progressNow,
         });
         setProgressMain(progressNow);
         stopAfterSeconds--;
    
         if (stopAfterSeconds === 0) {
          setFileContent({
           ...fileContent,
           [fileType]: file,
          });
    
          clearInterval(interval);
         }
        }
       }, 1000);
      }
     };
    
     useEffect(() => {
      console.log(fileContent);
     }, [fileContent]);
    
     return (
      <>
       <LoadingBar
        color="green"
        height={5}
        progress={progressMain}
        onLoaderFinished={() => setProgressMain(0)}
       />
       <Container pt={8} mt={8}>
        <Table size="sm">
         <Thead>
          <Tr>
           <Th>File Type</Th>
           <Th>Select File</Th>
           <Th isNumeric>Progress</Th>
          </Tr>
         </Thead>
         <Tbody>
          {/* Repeat the following code block for each file */}
          <Tr>
           <Td>File 1</Td>
           <Td>
            <input
             type="file"
             onChange={(event) => prepareFileForUpload(event, "fileOne")}
            />
           </Td>
           <Td isNumeric>
            <CircularProgress value={progress.fileOne} color="green.400">
             <CircularProgressLabel>
              {parseInt(String(progress.fileOne))}
             </CircularProgressLabel>
            </CircularProgress>
           </Td>
          </Tr>
          {/* End of code block */}
         </Tbody>
         <Tfoot>
          <Tr>
           <Th>File Type</Th>
           <Th>Select File</Th>
           <Th isNumeric>Progress</Th>
          </Tr>
         </Tfoot>
        </Table>
       </Container>
      </>
     );
    }
    


    4. That's it! You've created a React application with a file upload progress bar using Chakra UI and React Top Loading Bar.


    Running the Application


    To see your progress bar in action, run the following command in your project directory:


    npm start
    


    In this tutorial, you learned how to create a user-friendly file upload progress bar in a React application using the Chakra UI library and the React Top Loading Bar component. This can greatly enhance the user experience when dealing with file uploads, ensuring that your users are well-informed about the progress of their uploads. You can now expand upon this foundation to handle more file types and customize the interface to suit your application's needs. Happy coding!


    Packages you must install

    1. Chakra-ui.
    2. React top loading bar