react-parse-csv
v1.22.1
Published
Declarative CSV parser for react
Downloads
168
Readme
react-parse-csv
- Superfast CSV parser (uses papaparse internally).
- Validate your data using zod
- Declarative and automatic. Simply call
parse()
the rest is automatic. - Completely headless. Define your own styles!
Install
yarn
yarn add react-parse-csv papaparse zod
npm
npm install react-parse-csv papaparse zod
Example
import {useCsvParser, zodResolver} from "react-parse-csv";
import React, { useCallback } from "react";
import {FormEventHandler} from "react";
import { z } from "zod";
// Define a schema where each row should validate against:
const schema = z.object({
name: z.string().min(1),
address: z.string().min(1),
})
const MyComponent: React:FC = () => {
// Initialize hook.
const {data, errors, isValid, parse} = useCsvParser({resolver: zodResolver(schema)})
// Simple filechange handler:
const handleFileChange:FormEventHandler = useCallback((event) => {
parse(event.currentTarget.files[0])
}, [parse])
return (<>
<input type="file" onChange={handleFileChange}/>
{/* All rows were valid: */}
{ isValid && (
<table>
{ data.map(({name, address}, index) => (
<tr key={index}>
<td>{ name }</td>
<td>{ address }</td>
</tr>
) }
</table>
) }
{/* Some rows were invalid: */}
{ !isValid && (
<table>
{ errors.map(({line, column, message, value}, index) => (
<tr key={index}>
<td>{ line }</td>
<td>{ column }</td>
<td>{ message }</td>
<td>{ value }</td>
</tr>
) }
</table>
) }
</>)
}