• Stars
    star
    119
  • Rank 297,930 (Top 6 %)
  • Language
    TypeScript
  • License
    MIT License
  • Created over 4 years ago
  • Updated over 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

A csv file import button for react-admin

react-admin-import-csv

NPM Version Downloads/week License Github Issues Build and Publish Code Coverage

CSV import button for the react-admin framework.

image

Usage

Simply import the button into a toolbar, like so:

Basic Import Action Only

import {
  Datagrid,
  List,
  TextField,
  RichTextField,
  TopToolbar,
} from "react-admin";
import { ImportButton } from "react-admin-import-csv";
import { CreateButton } from "ra-ui-materialui";

const ListActions = (props) => {
  const { className, basePath } = props;
  return (
    <TopToolbar className={className}>
      <CreateButton basePath={basePath} />
      <ImportButton {...props} />
    </TopToolbar>
  );
};
export const PostList = (props) => (
  <List {...props} filters={<PostFilter />} actions={<ListActions />}>
    <Datagrid>
      <TextField source="title" />
      <RichTextField source="body" />
      ...
    </Datagrid>
  </List>
);

Export/Import Actions

import {
  Datagrid,
  List,
  TextField,
  RichTextField,
  TopToolbar,
} from "react-admin";
import { ImportButton } from "react-admin-import-csv";
import { CreateButton, ExportButton } from "ra-ui-materialui";

const ListActions = (props) => {
  const {
    className,
    basePath,
    total,
    resource,
    currentSort,
    filterValues,
    exporter,
  } = props;
  return (
    <TopToolbar className={className}>
      <CreateButton basePath={basePath} />
      <ExportButton
        disabled={total === 0}
        resource={resource}
        sort={currentSort}
        filter={filterValues}
        exporter={exporter}
      />
      <ImportButton {...props} />
    </TopToolbar>
  );
};
export const PostList = (props) => (
  <List {...props} filters={<PostFilter />} actions={<ListActions />}>
    <Datagrid>
      <TextField source="title" />
      <RichTextField source="body" />
      ...
    </Datagrid>
  </List>
);

Configuration Options

// All configuration options are optional
const config: ImportConfig = {
  // Enable logging
  logging?: boolean;
  // Disable the attempt to use "createMany", will instead just use "create" calls
  disableCreateMany?: boolean,
  // Disable the attempt to use "updateMany", will instead just use "update" calls
  disableUpdateMany?: boolean,
  // Disable the attempt to use "getMany", will instead just use "getSingle" calls
  disableGetMany?: boolean,
  // Disable "import new" button
  disableImportNew?: boolean;
  // Disable "import overwrite" button
  disableImportOverwrite?: boolean;
  // A function to translate the CSV rows on import
  preCommitCallback?: (action: "create" | "overwrite", values: any[]) => Promise<any[]>;
  // A function to handle row errors after import
  postCommitCallback?: (error: any) => void;
  // Transform rows before anything is sent to dataprovider
  transformRows?: (csvRows: any[]) => Promise<any[]>;
  // Async function to Validate a row, reject the promise if it's not valid
  validateRow?: (csvRowItem: any) => Promise<void>;
  // Any option from the "papaparse" library
  parseConfig?: {
    // For all options see: https://www.papaparse.com/docs#config
  }
}
<ImportButton {...props} {...config}/>

Handle id fields which might be numbers

Use the paparse configuration option dynamicTyping

const importOptions = {
  parseConfig?: {
    // For all options see: https://www.papaparse.com/docs#config
    dynamicTyping: true
  }
}

Reducing Requests (.createMany() and .updateMany())

Your dataprovider will need to implement the .createMany() method in order to reduce requests to your backend. If it doesn't exist, it will fallback to calling .create() on all items, as shown below (same goes for .update()):

Name Special Method Fallback Method
Creating from CSV .createMany() .create()
Updating from CSV .updateManyArray() .update()
Checking which exist .getMany() .getSingle()

Note: You can disable this feature setting disableCreateMany: true or disableUpdateMany: true in the configuration.

Interfaces

The dataprovider should accept these param interfaces for the bulk create/update methods.

export interface UpdateManyArrayParams {
  ids: Identifier[];
  data: any[];
}
export interface CreateManyParams {
  data: any[];
}

Example Implementation

Here's a quick example of how to implement .createMany() and .updateMany() in your dataprovider:

// Must be react-admin 3.x
const dataProviderWrapped = {
  ...dataProvider, // <- Your data provider
  createMany: async (resource, params) => {
    const items = params.data;
    // Handle create many here
  },
  updateMany: async (resource, params) => {
    const items = params.data;
    const idsToUpdate = params.ids;
    // Handle update many here
  }
}

// Pass into to other parts of the system as normal
return (
  <Admin dataProvider={dataProviderWrapped}

Translation i18n

This package uses react-admin's global i18n translation. Below is an example on how to set it up with this package.

Current supported languages (submit a PR if you'd like to add a language):

  • English (en)
  • Spanish (es)
  • Chinese (zh)
  • German (de)
  • French (fr)
  • Brazilian Portuguese (ptBR)
  • Russian (ru)
  • Dutch (nl)

Example (i18nProvider)

import { resolveBrowserLocale, useLocale } from "react-admin";
import polyglotI18nProvider from "ra-i18n-polyglot";
import englishMessages from "ra-language-english";
// This package's translations
import * as domainMessages from "react-admin-import-csv/lib/i18n";

// Select locale based on react-admin OR browser
const locale = useLocale() || resolveBrowserLocale();
// Create messages object
const messages = {
  // Delete languages you don't need
  en: { ...englishMessages, ...domainMessages.en },
  zh: { ...chineseMessages, ...domainMessages.zh },
  es: { ...spanishMessages, ...domainMessages.es },
};
// Create polyglot provider
const i18nProvider = polyglotI18nProvider(
  (locale) => (messages[locale] ? messages[locale] : messages.en),
  locale
);

// declare prop in Admin component
<Admin dataProvider={dataProvider} i18nProvider={i18nProvider}>

More information on this setup here

Development

If you'd like to develop on react-admin-import-csv do the following.

Local install

  • git clone https://github.com/benwinding/react-admin-import-csv/
  • cd react-admin-import-csv
  • yarn

Tests

  • yarn test # in root folder

Run demo

Open another terminal

  • yarn build-watch

Open another terminal and goto the demo folder

  • yarn start

More Repositories

1

react-admin-firebase

A firebase data provider for the react-admin framework
TypeScript
429
star
2

quill-html-edit-button

Quill.js Module which allows you to quickly view/edit the HTML in the editor
TypeScript
126
star
3

quill-image-compress

A Quill rich text editor Module which compresses images uploaded to the editor
TypeScript
100
star
4

ngext

Better routing for Angular
TypeScript
82
star
5

react-admin-firebase-demo

Demo project for the react-admin-firebase npm package
JavaScript
46
star
6

command-pal

The hackable command palette for the web, inspired by Visual Studio Code.
HTML
41
star
7

newsit

Chrome Extension for Hacker News and Reddit Links
TypeScript
21
star
8

example-jest-firestore-triggers

An example of using jest to test firestore triggers
JavaScript
19
star
9

pdfstamp

A cli tool to stamp PDF's, using (ImageMagick and pdftk)
JavaScript
19
star
10

vuex-trace

Log actions & mutations in vuex! πŸš€
JavaScript
12
star
11

wealth-visualizer

Wealth Visualizer
Vue
11
star
12

vuetify-datatable-extended

An extension of vuetify-datatable to make filters a bit easier
Vue
10
star
13

ngx-filemanager

File manager for Angular
TypeScript
8
star
14

dokku-pages

Simple static sites on Dokku!
JavaScript
8
star
15

react-admin-firebase-demo-typescript

Demo project for the react-admin-firebase npm package
TypeScript
8
star
16

scrape-reduce

A simple way to scrape websites
TypeScript
7
star
17

localnotes.page

A simple website to write notes, stored in browser
HTML
3
star
18

frank-the-collie

Frank the Collie
Svelte
3
star
19

Meme-Bot-Messenger-Client

A meme responding bot for facebook messenger
JavaScript
3
star
20

quill-image-rotate-module

A module for Quill rich text editor to allow images to be rotated.
JavaScript
3
star
21

ngx-auto-table

A simple to use data table for Angular
TypeScript
3
star
22

twingex

A simple export format for Twine text adventure games
HTML
2
star
23

jira-to-github

Migrate JIRA issues to Github
TypeScript
2
star
24

zoomore

Zoom pictures and turn them into gifs!!
Dart
2
star
25

benw-blog

Stylus
1
star
26

benw-portal

My website portal!
HTML
1
star
27

mat-reduce

Angular Material is verbose, here's a wrapper library to reduce that!
TypeScript
1
star
28

pat.dog

JavaScript
1
star
29

gatsby-starter-netlify-cms

JavaScript
1
star
30

doughculator

A calculator for Dough!
TypeScript
1
star
31

cloud-html2pdf

A small node server to convert HTML documents to PDF
HTML
1
star
32

benwinding

1
star
33

ycomments-landingpage

CSS
1
star
34

lenny.homes

A website for my homie Lenny!
TypeScript
1
star
35

newsit-landingpage

HTML
1
star
36

myuni-dl

Command-line tool to download all files from a MyUni course
Python
1
star
37

mat-firebase-upload

An easy to use upload dropzone for Angular/Firebase.
TypeScript
1
star
38

firecache

Client-side state-management using Firebase
TypeScript
1
star
39

LEDMatrix64-Arduino

Based on "tomaskovacik/arduino" but altered for a 64x32 pixel LED display
Objective-C
1
star