Loading...
Please waitLoading...
Please waitpnpm dlx uselab@latest add use-csv-import
import * as React from "react"
import { useCsvImport } from "@/hooks/use-csv-import"
interface UserRow {
name: string
email: string
age: string
}
export function Component() {
const [file, setFile] = React.useState<File | null>(null)
const { headers, rows, errors, loading } = useCsvImport<UserRow>(file, {
delimiter: ",",
skipEmptyLines: true,
})
const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
setFile(e.target.files?.[0] || null)
}
return (
<div
ref={dropRef}
onClick={() => inputRef.current?.click()}
role="button"
tabIndex={0}
style={{
border: isOverDropZone ? "2px dashed #6b46c1" : "2px dashed #ccc",
padding: 16,
borderRadius: 12,
}}
>
<input
ref={inputRef}
type="file"
accept=".csv"
onChange={handleFileChange}
style={{ display: "none" }}
/>
<p>
{isOverDropZone
? "Drop CSV here"
: "Drag & drop CSV or click to browse"}
</p>
{loading && <p>Parsing...</p>}
{errors.size > 0 && (
<div>
{Array.from(errors.entries()).map(([line, error]) => (
<p key={line}>
Line {line}: {error}
</p>
))}
</div>
)}
<div>
<p>Headers: {headers.join(", ")}</p>
</div>
<ul>
{rows.map((row, i) => (
<li key={i}>
{row.name} - {row.email}
</li>
))}
</ul>
</div>
)
}useCsvImport<T>(file, options?):
rows, errors, and loading state.Options:
delimiter: CSV delimiter (default: ",").skipEmptyLines: Whether to skip empty lines (default: true).Error Handling:
errors is a Map<number, string> where the key is the line number and the value is the error message.Type Safety:
| Name | Type | Description | Default Value | Optional |
|---|---|---|---|---|
file | File | null | The CSV file to parse. Set to null to clear the import. | - | No |
options | CsvImportOptions | Configuration options for parsing. | {} | Yes |
| Name | Type | Description | Default Value |
|---|---|---|---|
delimiter | string | The CSV delimiter character. | "," |
skipEmptyLines | boolean | Whether to skip empty lines during parsing. | true |
| Name | Type | Description |
|---|---|---|
rows | T[] | Array of parsed rows, typed according to the generic type parameter. |
errors | Map<number, string> | Map of line numbers to error messages for rows that failed to parse. |
loading | boolean | Whether the CSV file is currently being parsed. |
headers | string[] | Headers parsed from the first row (BOM-stripped). |
Drag CSV here or click to choose
Expected columns: name, email, age