How to import CSV Files with React
Tags: react, import, csv
Published: 2024-05-11 06:48:43

---
title: How to import CSV Files with React
published: true
description: Embed an import wizard into your application to help your users import their data.
tags: #react #import #csv
cover_image: https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0ugsm29h0pzywgn5pc5d.jpg
canonical_url: https://medium.com/@softius/how-to-import-csv-files-with-react-594867e5b81e
# Use a ratio of 100:42 for best results.
# published_at: 2024-05-11 06:30 +0000
---

In this article we are going to explore how we can use [importOK](https://importok.io/?utm_source=devto&utm_medium=blog&utm_campaign=react-import) to embed an import wizard into a React application. When we are done, we will be able to upload both CSV and Excel files, map the columns, review and fix any validation errors and finally submit the uploaded data to our API.

[importOK](https://importok.io/?utm_source=devto&utm_medium=blog&utm_campaign=react-import) is a reusable custom web component — you can control where it goes and how the mapping works. There are zero dependencies to any third party services and it can be hooked directly to your API.

## Setup your fields
For the sake of simplicity, we will be importing a list of Contacts. Our app will be expecting four fields: first name last name email and phone.
First, we need to install the React component for importOK.
npm install @importok/react
Then to embed the import wizard, we can add the following into our page.

```
import ImportokWizard from '@importok/react';
 
function App() {
  /**
    * Import fields to be mapped
    * Check https://importok.io/docs/fields.html for more details
    */
  const fields = {
    first_name: {
      label: 'First Name'
    },
    last_name: {
      label: 'Last Name'
    },
    email: {
      label: 'Email'
    },
    phone: {
      label: 'Phone'
    }
  };
 
  return (
    <div className="App">
      <ImportokWizard
        title="importOK Example for React"
        fields={fields}
      />
    </div>
  );
}
```

The above also [defines a list of fields](https://importok.io/docs/fields.html?utm_source=devto&utm_medium=blog&utm_campaign=react-import) which more or less describe our resource schema. Providing only the labels is sufficient and more than enough to get you started. Give it a go! At this stage you should be able to upload a CSV File and map the columns. Sweet eh?

![Uploading CSV Files and mapping columns](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/sww37798j76oq1ypdczf.gif)

## Normalize and Cleanup your data

More often than not, the data provided by your end-users is not in perfect shape. Extra trailing spaces, incorrectly formatted phone numbers, and other frequent irregularities that take time and effort to resolve.

To improve this, we can use [transformers](https://importok.io/docs/transformers.html?utm_source=devto&utm_medium=blog&utm_campaign=react-import) to apply common fixes. The transformation happens right after the file is uploaded and before the validation. importOK provides a handfull of built-in transformers but if necessary you can also add your own.

Let’s extend our example to trim any spaces, and capitalize both first and last name.

```
import ImportokWizard from '@importok/react';
 
function App() {
  /**
    * Import fields to be mapped
    * Check https://importok.io/docs/fields.html for more details
    */
  const fields = {
    first_name: {
      label: 'First Name',
      transformers: 'trim|capitalize'
    },
    last_name: {
      label: 'Last Name',
      transformers: 'trim|capitalize'
    },
    email: {
      label: 'Email',
      transformers: 'trim'
    },
    phone: {
      label: 'Phone',
      transformers: 'trim'
    }
  };
 
  return (
    <div className="App">
      <ImportokWizard
        title="importOK Example for React"
        fields={fields}
      />
    </div>
  );
}
```

## Validate your data

While transformers can help auto-heal your data, and bring consistency, they don’t cover all the cases. What if the email provided is invalid or the last name is blank?

[Validators](https://importok.io/docs/validators.html?utm_source=devto&utm_medium=blog&utm_campaign=react-import) have been designed to address this problem and provide instead feedback to your end-users, so that they can fix these errors. Similar to transformers, there are some build-in validators and you can add your own as well.

Let’s improve further our example to make the last name required, and ensure that both email and phone are in the right format.

```
import ImportokWizard from '@importok/react';
 
function App() {
  /**
    * Import fields to be mapped
    * Check https://importok.io/docs/fields.html for more details
    */
  const fields = {
    first_name: {
      label: 'First Name',
      transformers: 'trim|capitalize'
    },
    last_name: {
      label: 'Last Name',
      transformers: 'trim|capitalize',
      validators: 'required'
    },
    email: {
      label: 'Email',
      transformers: 'trim'
      validators: 'email'
    },
    phone: {
      label: 'Phone',
      transformers: 'trim'
      validators: 'phone'
    }
  };
 
  return (
    <div className="App">
      <ImportokWizard
        title="importOK Example for React"
        fields={fields}
      />
    </div>
  );
}
```

Here is how it looks like at this point. Please note that you can filter by error type and that you can adjust your data without leaving the import wizard.

![Reviewing, fixing and importing data](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/snkzrwevu0oo3fb4q0cr.gif)

## Push data to your API
There are a couple of options available to push the normalized and validated data to your API. You can either choose to send individuals records in parallel or send the full data set.

Let’s use the latter option for our example.

```
import ImportokWizard from '@importok/react';
 
function App() {
  /**
    * Import fields to be mapped
    * Check https://importok.io/docs/fields.html for more details
    */
  const fields = {
    first_name: {
      label: 'First Name',
      transformers: 'trim|capitalize'
    },
    last_name: {
      label: 'Last Name',
      transformers: 'trim|capitalize',
      validators: 'required'
    },
    email: {
      label: 'Email',
      transformers: 'trim'
      validators: 'email'
    },
    phone: {
      label: 'Phone',
      transformers: 'trim'
      validators: 'phone'
    }
  };

  /**
    * Push the normalized and validated records to the API
    * Check https://importok.io/docs/webhooks.html for more details
    */
  const importRecords = async function (records, meta) {
    return await fetch('https://your-api.com', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify(records)
      });
  };
 
  return (
    <div className="App">
      <ImportokWizard
        title="importOK Example for React"
        fields={fields}
        onImportReady={importRecords}
      />
    </div>
  );
}
```

## Add a CSV importer in your React app

importOK can be used to import data into your application, by embedding a powerful import wizard and leverage your existing API.

As a guideline, first you need to define the fields, so that your end users can map their data. Then you will need to define some transformers to normalize and clear the data to be imported. Next, you will need to define some validation rules so that you users can get instant feedback when something is wrong. Last, but not least, you will need register your webhooks so that you can actually import the data into your backend system.

importOK is available as a trial so that you can give it try before purchasing the pro license. At the moment of writing, you can [join early](https://importok.io/pricing.html?utm_source=devto&utm_medium=blog&utm_campaign=react-import) and benefit from a 67% discount, for early adopters.

Make sure to follow me on [dev.to](https://dev.to/iacons/), [Medium](https://medium.com/@softius) or [Twitter](https://twitter.com/iacons) to read more about importOK or [visit the website](https://importok.io/index.html?utm_source=devto&utm_medium=blog&utm_campaign=react-import) for more details.