Skip to content
This repository has been archived by the owner on Oct 5, 2024. It is now read-only.

Feature/upload field branch (draft) #116

Draft
wants to merge 6 commits into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions src/components/forms/UploadField.stories.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import { action } from '@storybook/addon-actions';
import { Meta, Story, Preview, Props } from '@storybook/addon-docs/blocks';
import UploadField from './UploadField';

<Meta title="Forms|UploadField" component={UploadField} />

# Upload field

This is an `<input />` field of `type="file"` in HTML.
It has support for multiple files being uploaded, as well as drag & drop.

<Preview>
<Story name="all">
<>
<h3>Upload file</h3>
<UploadField label="Upload file" />
</>
</Story>
</Preview>

<Props of={UploadField} />
65 changes: 65 additions & 0 deletions src/components/forms/UploadField.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
import React, { useState } from 'react';
import styled, { StyledComponentProps } from 'styled-components';
import { colors } from 'common/colors';

interface UploadFieldProps extends StyledComponentProps<'input', any, any, any> {
label: string;
}

const FileUpload = styled.input`
display: none;
`;
const FileUploadLabel = styled.label`
display: inline-block;
border-radius: 3px;
text-align: center;
background-color: ${colors.grayLighten90};
box-sizing: border-box;
border: 2px dashed ${colors.primary};
width: 400px;
padding: 20px 10px;
`;
const FileUploadContainer = styled.div`
display: flex;
`;
const RandomId = 'upload' + Math.floor(Math.random() * 1000);

const UploadField = ({ ...props }: UploadFieldProps) => {
const [text, setText] = useState('');

const fileChange = (files: any[]) => {
let build = '';
for (let file of files) {
build += ', ' + file.name;
}
setText(build.slice(2));
};

const handleFileChange = (evt: any) => {
if (evt.target && evt.target.files) {
fileChange(evt.target.files);
}
};

const handleDragOver = (e: any) => {
e.preventDefault();
e.stopPropagation();
};
const handleDrop = (e: any) => {
e.preventDefault();
e.stopPropagation();

fileChange(e.dataTransfer.files);
};

return (
<FileUploadContainer>
<FileUpload id={RandomId} type="file" multiple onChange={handleFileChange} {...props} />
<FileUploadLabel htmlFor={RandomId} onDragOver={handleDragOver} onDrop={handleDrop}>
{props.label} {text}
</FileUploadLabel>
</FileUploadContainer>
);
};

export default UploadField;