Drop zone
An upload area that accepts files by drag-and-drop or from the file browser, with a DropZone.FileUpload call to action and a list of the files that were accepted.
Preview
Code
Example.jsx
import { useState, useCallback } from 'react';
import { Card, BlockStack, InlineStack, Text, DropZone, Thumbnail, Banner, Button } from '@shopify/polaris';
import { NoteIcon } from '@shopify/polaris-icons';
const INITIAL_FILES = [
{ name: 'winter-catalog.csv', size: 48210 },
{ name: 'product-photos.zip', size: 2411520 },
];
const SIZE_UNITS = ['B', 'KB', 'MB', 'GB'];
const formatFileSize = (bytes) => {
let value = bytes;
let unit = 0;
while (value >= 1024 && unit < SIZE_UNITS.length - 1) {
value = value / 1024;
unit += 1;
}
const rounded = unit === 0 ? value : Math.round(value * 10) / 10;
return `${rounded} ${SIZE_UNITS[unit]}`;
};
export const Example = () => {
const [files, setFiles] = useState(INITIAL_FILES);
const [rejectedCount, setRejectedCount] = useState(0);
const handleDrop = useCallback((_dropFiles, acceptedFiles, rejectedFiles) => {
setFiles((current) => [...current, ...acceptedFiles]);
setRejectedCount(rejectedFiles.length);
}, []);
const removeFile = useCallback((name) => {
setFiles((current) => current.filter((file) => file.name !== name));
}, []);
const fileList = files.length > 0 && (
<BlockStack gap="200">
{files.map((file) => (
<InlineStack key={file.name} gap="300" blockAlign="center" align="space-between" wrap={false}>
<InlineStack gap="300" blockAlign="center" wrap={false}>
<Thumbnail size="small" alt={file.name} source={NoteIcon} />
<BlockStack gap="050">
<Text as="span" fontWeight="medium">
{file.name}
</Text>
<Text as="span" variant="bodySm" tone="subdued">
{formatFileSize(file.size)}
</Text>
</BlockStack>
</InlineStack>
<Button variant="plain" tone="critical" onClick={() => removeFile(file.name)}>
Remove
</Button>
</InlineStack>
))}
</BlockStack>
);
return (
<Card>
<BlockStack gap="300">
<Text as="h2" variant="headingMd">
Import products
</Text>
{rejectedCount > 0 && (
<Banner tone="critical" title="Some files could not be uploaded" onDismiss={() => setRejectedCount(0)}>
<Text as="p">{rejectedCount} file(s) were rejected because the type is not supported.</Text>
</Banner>
)}
<DropZone onDrop={handleDrop} accept=".csv,.zip,image/*" outline>
<DropZone.FileUpload actionTitle="Add files" actionHint="or drop CSV, ZIP and image files to upload" />
</DropZone>
{fileList}
<Text as="p" variant="bodySm" tone="subdued">
{files.length} file{files.length === 1 ? '' : 's'} ready to import
</Text>
</BlockStack>
</Card>
);
};