---
title: Import CSV & Excel Files in React
description: A step-by-step guide to building a production-ready CSV importer that handles real-world data
date: 2024-11-10
icon: react
---

Whether you're migrating from a legacy system, onboarding enterprise customers with existing data, modernizing an internal tool, or building a SaaS product data import is unavoidable. And it's always harder than it looks.

Here's what every import flow deals with:

- Files arrive with inconsistent column names ("Email" vs "email" vs "E-mail Address")
- Data is messy (extra spaces, inconsistent capitalization, malformed values)
- You need validation before import (or deal with broken data in production)
- Edge cases multiply (Excel vs CSV, different date formats, special characters, encoding issues)

Building this from scratch takes weeks of edge case handling. Let's do it in 5 minutes instead.

## What we're building

By the end of this tutorial, you'll have:

- ✅ File upload for CSV and Excel
- ✅ Smart column mapping (with AI assistance)
- ✅ Automatic data cleanup
- ✅ Real-time validation with user feedback
- ✅ Integration with your existing API

**See it in action:** [Live demo on StackBlitz →](https://stackblitz.com/~/github.com/importok/react-example)

## Step 1: Install importOK

```bash
npm install @importok/javascript @importok/react
```

## Step 2: Create your first importer

Let's say you're building a CRM and need to import contacts. Add the import wizard to your component:

```jsx
import ImportokWizard from '@importok/react';

export default function ImportContacts() {
  const fields = {
    first_name: { label: 'First Name' },
    last_name: { label: 'Last Name' },
    email: { label: 'Email' },
    phone: { label: 'Phone' },
    country: { label: 'Country' }
  };
  
  return (
    
      Import Contacts
      
    
  );
}
```

**What just happened?**

- You defined your data model with `fields`
- The wizard automatically handles file upload, parsing, and column mapping
- Users can map "First Name" → "first_name" even if their CSV says "Given Name"

![Column mapping demo](/assets/import-csv-react-1.gif)

## Step 3: Handle messy data

Real-world CSV files are never clean. Here's what you typically see:

```csv
First Name,Last Name,Email
  John  , smith ,JOHN.SMITH@GMAIL.COM
mary,JONES  ,mary@example.com  
```

Notice the problems? Extra spaces, inconsistent capitalization, uppercase emails. Let's fix this automatically with transformers:

```jsx
const fields = {
  first_name: {
    label: 'First Name',
    transformers: 'trim|capitalize'
  },
  last_name: {
    label: 'Last Name',
    transformers: 'trim|capitalize'
  },
  email: {
    label: 'Email',
    transformers: 'trim|lowercase'  // Emails should be lowercase
  },
  phone: {
    label: 'Phone',
    transformers: 'trim'
  },
  country: {
    label: 'Country',
    transformers: 'trim'
  }
};
```

Now that messy data becomes:
```
John,Smith,john.smith@gmail.com
Mary,Jones,mary@example.com
```

**How it works:** Transformers run immediately after file upload, before users see the data. Users can still edit if needed, but most cleanup happens automatically.

[See all built-in transformers →](/docs/transformers)

## Step 4: Add validation rules

Cleanup helps, but you still need to catch invalid data. Let's add validators:

```jsx
const fields = {
  first_name: {
    label: 'First Name',
    transformers: 'trim|capitalize'
  },
  last_name: {
    label: 'Last Name',
    transformers: 'trim|capitalize',
    validators: 'required'  // Can't be empty
  },
  email: {
    label: 'Email',
    transformers: 'trim|lowercase',
    validators: 'email|required'  // Must be valid email format
  },
  phone: {
    label: 'Phone',
    transformers: 'trim',
    validators: 'phone'  // Optional but must be valid if provided
  },
  country: {
    label: 'Country',
    transformers: 'trim',
    validators: 'in:countries'  // Must be a valid country
  }
};
```

**The user experience:**

- Invalid rows are highlighted in red
- Users can filter by error type
- They can fix errors inline without re-uploading
- Only valid data reaches your API

![Validation demo](/assets/import-csv-react-2.gif)

[See all built-in validators →](/docs/validators)

## Step 5: Send data to your API

Now let's actually import the data. You have two options:

### Option A: Batch import

Send all records at once. Best for most use cases:

```jsx
export default function ImportContacts() {
  const fields = { /* ... */ };

  const handleBatchImport = async (records, meta) => {
    try {
      const response = await fetch('/api/contacts/import', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          contacts: records,
          total: meta.totalRecords
        })
      });

      if (!response.ok) {
        throw new Error('Import failed');
      }

      // Show success message
      return response;
    } catch (error) {
      console.error('Import error:', error);
      throw error;
    }
  };
  
  return (
    
  );
}
```

### Option B: Individual records

Send records one at a time. Better for long-running imports or when you need to show progress:

```jsx
const handleRecordImport = async (record, meta) => {
  const response = await fetch('/api/contacts', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(record)
  });
  
  return response;
};

return (
  
);
```

## Real-world example: CRM contact import

Let's put it all together with a complete example:

```jsx
import ImportokWizard from '@importok/react';
import { useState } from 'react';

export default function ImportContacts() {
  const fields = {
    first_name: {
      label: 'First Name',
      transformers: 'trim|capitalize',
      validators: 'required'
    },
    last_name: {
      label: 'Last Name',
      transformers: 'trim|capitalize',
      validators: 'required'
    },
    email: {
      label: 'Email',
      transformers: 'trim|lowercase',
      validators: 'email|required'
    },
    phone: {
      label: 'Phone',
      transformers: 'trim'
    },
    company: {
      label: 'Company',
      transformers: 'trim'
    },
    country: {
      label: 'Country',
      transformers: 'trim',
      validators: 'in:countries'
    }
  };

  const handleImport = async (records, meta) => {
    
    try {
      const response = await fetch('/api/contacts/import', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ contacts: records })
      });

      const data = await response.json();

      return response;
    } catch (error) {
      throw error;
    }
  };
  
  return (
    
      Import Contacts
      
      
    
  );
}
```

## Going further

### Custom validation rules

Need business-specific validation? Create custom validators:

```jsx
const customValidators = {
  // Validate phone numbers match your format
  phone: (value) => {
    if (!/^\+1-\d{3}-\d{3}-\d{4}$/.test(value)) {
      return 'Phone must be in format: +1-555-123-4567';
    }

    return true;
  },
  
  // Check against your database
  email_not_exists: async (value) => {
    const response = await fetch(`/api/contacts?email=${value}`);
    const { exists } = await response.json();
    if (exists) {
      return 'This email already exists in your CRM';
    }

    return true;
  }
};

const fields = {
  email: {
    label: 'Email',
    transformers: 'trim|lowercase',
    validators: 'email|required|email_not_exists'
  },
  phone: {
    label: 'Phone',
    transformers: 'trim',
    validators: 'phone'
  }
};


```

[Learn more about custom validators →](/docs/validators)

### Custom transformations

Need domain-specific data cleanup? Create custom transformers:

```jsx
const customTransformers = {  
  // Standardize company names
  company: (value) => {
    return value
      .replace(/\bInc\b/gi, 'Inc.')
      .replace(/\bLLC\b/gi, 'LLC')
      .replace(/\bLtd\b/gi, 'Ltd.');
  }
};

const fields = {
  company: {
    label: 'Company',
    transformers: 'trim|company'
  }
};


```

[Learn more about custom transformers →](/docs/transformers)

### Connect to your database

Use data providers to populate dropdowns from your API:

```jsx
const dataProviders = {
  // Load sales reps from your database
  sales_reps: {
    // Get a single sales representative  ID
    get: async function (query) {
      const response = await fetch('/api/sales-reps/' + query + ');
      if (!response.ok) {
        throw new Error(`Response status ${response.status}`);
      }

      const data = await response.json();

      return {
        value: data.id,
        label: data.name
      };
    },
    // Find multiple sales representatives matching the provided name
    find: async function (query) {
      const response = await fetch('/api/sales-reps?name=' + query + ');
      if (!response.ok) {
        throw new Error(`Response status ${response.status}`);
      }

      const data = await response.json();
      return data.map(item => ({
        value: item.id,
        label: item.name
      }));
    },
  },
};

const fields = {
  // ... other fields
  assigned_to: {
    label: 'Assigned To',
    validators: 'required|in:sales_reps'
  },
};


```

[Learn more about data providers →](/docs/data-providers)

## Next steps

You now have a production-ready CSV importer. Here's what to explore next:

- **[Field configuration](/docs/fields)** - Advanced field options
- **[Component props and events](/docs/component-props-events)** - Customize behavior
- **[Styling and branding](/docs/styling)** - Match your design system

## Free trial limitations

The trial version is fully functional with these limits:

- ✅ Full UI and mapping features
- ✅ Built-in validators and transformers
- ⚠️ **20 records per import** (unlimited on paid plans)
- ⚠️ **Up to 2 custom validators** (unlimited on paid plans)
- ⚠️ **Up to 2 custom transformers** (unlimited on paid plans)
- ⚠️ **Up to 2 data providers** (unlimited on paid plans)

[See pricing and upgrade options →](/pricing)
