csv-import Documentation

repository·main·Indexed 23 days ago

https://github.com/tableflowhq/csv-import

An open-source CSV, TSV, and XLS/XLSX file importer for React and vanilla JavaScript. It provides a guided UI for users to map file columns to application-defined schemas via the csv-import-react and csv-import-js SDKs. Features include customizable import templates, internationalization (i18n) support, dark mode, and flexible styling options.

Tokens
5.1K
Snippets
14
Records
19
Agent score
83%

What's inside csv-import

  1. Set up the Demo project locally

    main

    To run the demo project with the local version of the csv-import package, you must use yalc to link the package locally.

    1. Install yalc globally: yarn global add yalc.
    2. Build and publish the package locally from the project root: yarn build && yalc publish.
    3. Navigate to the demo/ directory and add the package: yalc add csv-import.
    yarn global add yalc
    yarn build && yalc publish
    cd demo/
    yalc add csv-import
  2. Install the CSV Importer SDK

    main

    You can install the SDK for either React or vanilla JavaScript using NPM or Yarn.

    For React: Install csv-import-react.

    For JavaScript: Install csv-import-js or include it via unpkg in your HTML.

    # React
    npm install csv-import-react
    yarn add csv-import-react
    
    # JavaScript
    npm install csv-import-js
    yarn add csv-import-js
  3. Implement Internationalization (i18n)

    main

    The importer supports predefined languages via the language prop (e.g., language="fr" for French). Predefined languages include en, es, and fr.

    You can also provide customTranslations to support any language by defining a mapping of labels and messages. Use the language prop to point to your custom key.

    // Set up custom translations
    const customTranslations = {
      jp: {
        Upload: "アップロード",
        "Browse files": "ファイルを参照",
      },
      pt: {
        Upload: "Carregar",
        "Browse files": "Procurar arquivos",
      },
    };
    
    return (
      <CSVImporter language="jp" customTranslations={customTranslations} ...props />
    )
  4. Customize the importer UI with customStyles

    main

    Use the customStyles object to override default colors and spacing. Custom styles take precedence over primaryColor and darkMode settings. Supported keys include:

    • font-family, font-size, base-spacing, border-radius
    • color-primary, color-primary-hover
    • color-secondary, color-secondary-hover
    • color-tertiary, color-tertiary-hover
    • color-border
    • color-text, color-text-soft, color-text-on-primary
    • color-background, color-background-modal, color-input-background, color-input-background-soft
    • color-background-menu-hover
    • color-importer-link
    • color-progress-bar
    customStyles={{
      "font-family": "cursive",
      "font-size": "15px",
      "base-spacing": "2rem",
      "border-radius": "8px",
      "color-primary": "salmon",
      "color-primary-hover": "crimson",
      "color-secondary": "indianRed",
      "color-secondary-hover": "crimson",
      "color-tertiary": "indianRed",
      "color-tertiary-hover": "crimson",
      "color-border": "lightCoral",
      "color-text": "brown",
      "color-text-soft": "rgba(165, 42, 42, .5)",
      "color-text-on-primary": "#fff",
      "color-text-on-secondary": "#ffffff",
      "color-background": "bisque",
      "color-background-modal": "blanchedAlmond",
      "color-input-background": "blanchedAlmond",
      "color-input-background-soft": "white",
      "color-background-menu-hover": "bisque",
      "color-importer-link": "indigo",
      "color-progress-bar": "darkGreen"
    }}
  5. Configure the import template

    main

    The template object defines the columns the user is expected to map. Each column in the columns array can be configured with:

    • name: The display name of the column.
    • key: The key used in the resulting data object.
    • required: Boolean indicating if the column must be mapped.
    • description: A description for the user.
    • suggested_mappings: An array of strings representing common header names to help auto-mapping.
    • multiple: (Boolean) If true, allows multiple source columns to be mapped to this single destination column.
    • combiner: (Function) A function used to combine values from multiple source columns when multiple is true. Defaults to joining with a space.
    template={{
      columns: [
        {
          name: "First Name",
          key: "first_name",
          required: true,
          description: "The first name of the user",
          suggested_mappings: ["First", "Name"],
        },
        {
          name: "Age",
        },
        {
          name: "Category",
          multiple: true,
          combiner: (values: string[]) => values.join(' | '),
        }
      ],
    }}
  6. Use the CSVImporter component in React

    main

    To use the importer in a React application, import CSVImporter and manage its visibility using state. You must provide a template to define the expected columns and an onComplete callback to receive the parsed data.

    import { CSVImporter } from "csv-import-react";
    import { useState } from "react";
    
    function MyComponent() {
      const [isOpen, setIsOpen] = useState(false);
    
      return (
        <>
          <button onClick={() => setIsOpen(true)}>Open CSV Importer</button>
    
          <CSVImporter
            modalIsOpen={isOpen}
            modalOnCloseTriggered={() => setIsOpen(false)}
            darkMode={true}
            onComplete={(data) => console.log(data)}
            template={{
              columns: [
                {
                  name: "First Name",
                  key: "first_name",
                  required: true,
                  description: "The first name of the user",
                  suggested_mappings: ["First", "Name"],
                },
                {
                  name: "Age",
                },
              ],
            }}
          />
        </>
      );
    }
  7. Use the CSVImporter in vanilla JavaScript

    main

    For non-React projects, include the csv-import-js script via unpkg. Use CSVImporter.createCSVImporter() to initialize the importer by providing a domElement and configuration options. You can control the modal using .showModal() and .closeModal() methods on the returned instance.

    <head>
      <script src="https://unpkg.com/csv-import-js@latest/index.js"></script>
    </head>
    <body>
      <button id="uploadButton">Open CSV Importer</button>
      <div id="app"></div>
      <script>
        const importer = CSVImporter.createCSVImporter({
          domElement: document.getElementById("app"),
          modalOnCloseTriggered: () => importer?.closeModal(),
          onComplete: (data) => console.log(data),
          darkMode: true,
          template: {
            columns: [
              {
                name: "First Name",
                key: "first_name",
                required: true,
                description: "The first name of the user",
                suggested_mappings: ["First", "Name"],
              },
              {
                name: "Age",
              },
            ],
          },
        });
    
        const uploadButton = document.getElementById("uploadButton");
        uploadButton.addEventListener("click", () => {
          importer?.showModal();
        });
      </script>
    </body>
  8. Handle completed import data with onComplete

    main

    The onComplete callback is triggered when a user finishes the import process. It receives a data object containing the parsed rows and column metadata.

    {
      "num_rows": 2,
      "num_columns": 3,
      "columns": [
        {
          "key": "age",
          "name": "Age"
        },
        {
          "key": "email",
          "name": "Email"
        },
        {
          "key": "first_name",
          "name": "First Name"
        }
      ],
      "rows": [
        {
          "index": 0,
          "values": {
            "age": 23,
            "email": "maria@example.com",
            "first_name": "Maria"
          }
        },
        {
          "index": 1,
          "values": {
            "age": 32,
            "email": "robert@example.com",
            "first_name": "Robert"
          }
        }
      ]
    }
  9. Configure Chakra theme settings

    main

    When customizing the theme for the CSV importer using Chakra UI, you can provide a ThemeConfig object via the config property in the ChakraTheme interface. This allows you to control color mode behavior and CSS variable prefixes.

    Key configuration options include:

    • initialColorMode: Set to 'light', 'dark', or 'system'.
    • useSystemColorMode: A boolean to determine if the system preference should be used.
    • disableTransitionOnChange: A boolean to disable transitions when the color mode changes.
    • cssVarPrefix: A string to define a custom prefix for CSS variables.
  10. Reference: SDK Configuration Options

    main

    The following options are available for configuring the CSVImporter:

    • isModal (boolean, default: true): If true, the importer behaves as a modal controlled by modalIsOpen. If false, it is embedded directly in the page.
    • modalIsOpen (boolean, default: false): (React only) Controls the open state of the modal. For JS SDK, use .showModal()/.closeModal().
    • modalOnCloseTriggered (function): (Only if isModal is true) Callback when the user closes the modal via the close button or outside click.
    • modalCloseOnOutsideClick (boolean, default: false): (Only if isModal is true) If true, clicking outside the modal triggers modalOnCloseTriggered.
    • darkMode (boolean, default: false): Toggles dark/light mode.
    • primaryColor (string): Hex color for the primary UI elements.
    • showDownloadTemplateButton (boolean, default: true): If false, hides the Download Template button.
    • skipHeaderRowSelection (boolean, default: false): If true, skips the Header Row Selection step and assumes the first row is the header.