csv-preview.tsx
Overview
csv-preview.tsx is a React functional component file designed to fetch, parse, and display CSV (Comma-Separated Values) files from a given URL. It provides a user-friendly preview of CSV data as a styled HTML table. The component handles asynchronous data loading with visual feedback (loading spinner), error handling for file fetch or parse failures, and a clean tabular presentation with headers and rows.
This component is useful in applications where users need to quickly view CSV content without downloading or using external tools, such as document management systems, data dashboards, or file explorers.
Component: CSVFileViewer
Description
CSVFileViewer is a React Functional Component that:
Takes a CSV file URL as a prop.
Fetches the CSV file asynchronously using a custom
requestutility.Parses the CSV content into headers and rows.
Displays the CSV data in a styled table.
Shows a loading spinner while fetching/parsing.
Handles errors gracefully by showing error messages.
Props
Name | Type | Required | Description |
|---|---|---|---|
|
| Yes | The URL from which the CSV file is fetched and previewed. |
|
| No | Optional additional CSS classes to apply to the container. (Currently unused in component.) |
State
State | Type | Description |
|---|---|---|
| [CSVData \ | null](/projects/311/73394) |
|
| Indicates whether the CSV file is currently being loaded and parsed. |
Internal Types
interface CSVData {
rows: string[][];
headers: string[];
}
headers: An array of strings representing the CSV header row.
rows: An array of arrays of strings representing the CSV data rows.
Methods and Functions
parseCSV(csvText: string): CSVData
Parses raw CSV text into structured data with headers and rows.
Parameters:
csvText(string): Raw CSV text content.
Returns:
CSVDataobject containing:headers: Array of header strings.rows: Array of rows, each being an array of cell strings.
Details:
Splits the CSV text by newline characters.
Extracts the first line as headers, splitting by commas and trimming whitespace.
Processes subsequent lines similarly into rows.
Note: This is a basic CSV parser and does not handle quoted commas or multiline fields.
Usage Example:
const csvText = "Name, Age\nJohn Doe, 30\nJane Smith, 25"; const parsed = parseCSV(csvText); // parsed.headers -> ['Name', 'Age'] // parsed.rows -> [['John Doe', '30'], ['Jane Smith', '25']]
React Lifecycle and Effects
useEffect hook:
Runs on component mount and whenever the
urlprop changes.Invokes
loadCSVasync function to fetch and parse CSV file.Uses the
requestutility to GET the file as a blob.Uses
FileReaderto read the blob as text.Parses the CSV content using
parseCSV.On success, updates
datastate with parsed CSV.On failure, displays error messages via
message.error.Always sets
isLoadingto false after attempt.Cleans up by resetting
datato null on unmount or url change.
Render Output
Container Div
Ref:
containerRef(unused in logic but available for potential enhancements).CSS classes applied include base styling, padding, border, rounded corners, and scroll overflow.
Loading State
Shows a centered
<Spin />spinner component while loading.
Data Loaded
Renders a
<table>element:<thead>with header cells.<tbody>with rows and cells.
Empty cells display
'-'.
No Data and Not Loading
Renders nothing (
null).
Usage Example
import CSVFileViewer from './csv-preview';
function App() {
return (
<div style={{ height: '500px', width: '700px' }}>
<CSVFileViewer url="https://example.com/sample.csv" />
</div>
);
}
Important Implementation Details
CSV Parsing:
The parser is simple and assumes CSV is well-formed without commas inside quoted cells.
For complex CSV, consider replacing with a robust CSV parsing library (e.g., PapaParse).
File Loading:
Uses a custom
requestfunction (likely wrappingfetchoraxios) to retrieve the file.Downloads the file as a blob to handle binary data safely.
FileReaderis used to read blob content as text asynchronously.
Error Handling:
On fetch failure, shows "file load failed".
On parse failure, shows "CSV file parse failed".
Errors are logged to the console for debugging.
Styling:
Uses utility CSS classes (likely TailwindCSS or similar).
Applies scrollable container with max height to prevent overflow.
Integration and Interaction with Other Modules
message: Imported from@/components/ui/message- used to display user feedback on errors.Spin: Loading spinner component from@/components/ui/spin.request: Utility to make HTTP requests from@/utils/request.classNames: Utility for conditional CSS classes.React hooks:
useEffect,useState,useReffor lifecycle and state management.
This component can be embedded in any React page or component that needs to display CSV previews. It relies on the request utility to fetch files and UI components for consistent feedback and styling.
Mermaid Component Diagram
componentDiagram
component CSVFileViewer {
+props: { url: string, className?: string }
+state: { data: CSVData | null, isLoading: boolean }
+parseCSV(csvText: string): CSVData
+useEffect(loadCSV)
+render(): JSX.Element
}
component request
component message
component Spin
CSVFileViewer --> request : fetch CSV blob
CSVFileViewer --> message : show error messages
CSVFileViewer --> Spin : show loading spinner
Summary
csv-preview.tsx provides a complete React solution for asynchronously loading and previewing CSV files.
It features basic CSV parsing, loading state management, error handling, and styled rendering.
Designed to integrate smoothly with the application’s request and UI components.
Ideal for use cases needing quick CSV data previews without additional dependencies.
End of documentation.