A coding coach that I had at Flatiron school once recommended I develop a habit for posting content on dev.to as a way to continue to stay connected with the greater programming community. Well, its been about a month since my last post largely because I was dedicated to producing a few technical projects. What better way to get back into the habit than to show a simple and useful library for react that allows users to import data in a user-friendly medium: CSV parsing!
The set-up is fairly simple. Start by bringing the package into your react app:
npm install --save react-papaparse
Then you import the library into the component you want to use the library for:
Then, we create an element with a couple key events and functions that are necessary in the react element:
Let me explain: we need call the inputRef function to tell the PapaParse library that we would like to input a file. This will automatically open up a file browser to select a local CSV file from your machine. Once the file is selected in will automatically convert the delimited data into JSON. Please note that the data will be streamed exactly based on the index in the CSV and will disregard anything resembling column headers. If headers are required for your app there is a way to do so passing the following in the elements JSX:
'configOptions= header: true '
The next important piece is the onLoaded event, which we can use to pass the data to a function and actually use the data for whatever we would like. For my purposed I take that data and use it to post to my backend to create products for display. Like so:
As I hope is clear from the above, as long as the data is structured, it is relatively simple to send the data exactly where you want it. Easy!