How to read CSV files in the typescript react app?

mahdi_falamarzi

Mahdi Falamarzi

Posted on July 19, 2022

How to read CSV files in the typescript react app?

A comma-separated values (CSV) file is a delimited text file that uses a comma to separate values. Each line of the file is a data record. Each record consists of one or more fields, separated by commas. The use of the comma as a field separator is the source of the name for this file format. A CSV file typically stores tabular data (numbers and text) in plain text, in which case each line will have the same number of fields. Wiki
In this article, we want to read a CSV file in react application and for this, we use Papa Parse package. Papa Parse is the fastest in-browser CSV (or delimited text) parser for JavaScript.
Let's div in. First, we should install the package.



npm install papaparse


Enter fullscreen mode Exit fullscreen mode

while this project is created with typescript we should install the typescript package.



npm install @types/papaparse –-save-dev


Enter fullscreen mode Exit fullscreen mode

One important thing about the CSV files in react app that is the CSV file should be copied to the public directory.

copy csv file in public directory

Then we must import Papa Parse.



import Papa, { ParseResult } from "papaparse"


Enter fullscreen mode Exit fullscreen mode

ParseResult is papaparse type for result.
Then we define type of data.



type Data = {
  name: string
  family: string
  email: string
  date: string
  job: string
}

type Values = {
  data: Data[]
}


Enter fullscreen mode Exit fullscreen mode

after that, we create the state.



const [values, setValues] = React.useState<Values | undefined>()


Enter fullscreen mode Exit fullscreen mode

and create a function for getting csv file with Papa Parse package.



const getCSV = () => {
    Papa.parse("/file.csv", {
      header: true,
      download: true,
      skipEmptyLines: true,
      delimiter: ",",
      complete: (results: ParseResult<Data>) => {
        setValues(results)
      },
    })
  }


Enter fullscreen mode Exit fullscreen mode

and put it in useEffect hook.



 React.useEffect(() => {
    getCSV()
  }, [])


Enter fullscreen mode Exit fullscreen mode

That’s it. But for re-usability and separation of concerns reasons, we can create a custom hook.

useReadCSV custom hook

conclusion

Reading and importing CSV files into the application is a challenge. In this article, we use Papa Parse. This is a great package for importing, reading, etc... CSV files in js applications. For more information about this package see the blog Papa Parse.

💖 💪 🙅 🚩
mahdi_falamarzi
Mahdi Falamarzi

Posted on July 19, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related