In this blog post, we'll take a deep dive into a React component -->ExcelFilePreview designed to handle and preview Excel files, enabling users to preview Excel data before deciding to upload it. We'll dissect the code step by step to understand its functionality.
Introduction
The ExcelFilePreview component is built using React and relies on the xlsx library for Excel file handling. It provides users with a modal interface that displays the contents of an Excel file, empowering them to preview the data before making an upload decision. Let's explore the code that makes this happen.
Importing Dependencies
Component Definition
The ExcelFilePreview component is defined as a functional React component that accepting the props: file, onClose, and uploadFunction.
file: Represents the Excel file that users want to preview.
onClose: A callback function to close the modal.
uploadFunction: A function responsible for uploading the selected Excel file from other components.
State Management
excelData: state variable holds the data extracted from the Excel file.
loading: indicates whether the file is still being processed.
progress: This variable represents the progress of processing the file, ranging from 0 to 100%.(counter++)
Handling File Processing with useEffect
useEffect hook, component that handles the processing of the Excel file.
FileReader - created to read the content of the Excel file.
When the reader finishes loading the file, it converts the data into a Uint8Array.
The xlsx library is used to parse the Excel data, extract the first sheet, and convert it into a JSON format.
The extracted data is stored in the excelData state variable.
During processing, a loading animation is displayed, and the progress variable is updated incrementally to reflect the file processing progress.
After processing, the loading state is set to false.
Handling Form Submission
handleSubmit function is called when the user decides to upload the Excel file. It checks if excelData contains data, indicating that the file has been processed. If data is available, it triggers the uploadFunction to upload the file and closes the modal using the onClose callback.
Displaying the Modal
The above code is defined with the return statement
It displays the file name without the .xlsx extension(in the fileName heading).
During processing, a loading spinner and progress percentage are shown.
Once processing is complete, a table displays the Excel data.
Buttons are provided for uploading the file and closing the modal.