Skip to content

Instantly share code, notes, and snippets.

@samundrak
Last active December 21, 2021 11:35
Show Gist options
  • Save samundrak/75ec3090aeff204be0d84e8c65ad0393 to your computer and use it in GitHub Desktop.
Save samundrak/75ec3090aeff204be0d84e8c65ad0393 to your computer and use it in GitHub Desktop.
Formik, ReactHooks, TypeScript, Antd
import React, { useState, useReducer } from 'react';
import {
Form as FormikForm,
Formik,
Field,
FieldProps,
ErrorMessage,
} from 'formik';
import { Form, Upload, Button, Icon, AutoComplete } from 'antd';
import SimpleError from './SimpleError';
import { fontUploadRule } from '../rules';
import { UploadChangeParam } from 'antd/lib/upload';
import { UploadFile } from 'antd/lib/upload/interface';
import { SelectValue } from 'antd/lib/select';
type Props = {
onFontUpload: (
data: {
style: string;
weight: string;
file: UploadFile;
},
done: () => void,
) => void;
};
type State = {
style: string;
weight: string;
};
const intialState: State = {
style: '',
weight: '',
};
const styles = ['Regular', 'Normal', 'Italic'];
const weights = ['Bold', 'Lighter', 'Bolder', 'Normal'];
const FontUploadForm = ({ onFontUpload }: Props) => {
const [fileList, handleFile] = useState<UploadFile[]>([]);
return (
<Formik
validationSchema={fontUploadRule}
initialValues={intialState}
onSubmit={(e, { resetForm }) => {
onFontUpload(
{
file: fileList[0],
...e,
},
() => {
handleFile([]);
resetForm();
},
);
}}
render={() => (
<FormikForm>
<Field
type="file"
name="font"
render={({ field }: FieldProps) => (
<Form.Item label="Font">
<Upload
onRemove={() => handleFile([])}
fileList={fileList || []}
multiple={false}
onChange={(e: UploadChangeParam) => handleFile([e.file])}
beforeUpload={() => false}
>
<Button>
<Icon type="upload" /> Click to Upload
</Button>
</Upload>
</Form.Item>
)}
/>
<Field
type="text"
name="style"
render={({ field }: FieldProps) => (
<Form.Item label="Style">
<AutoComplete
{...field}
onChange={(value: SelectValue) => {
field.onChange({
target: { value, name: 'style', id: 'style' },
});
}}
dataSource={styles}
placeholder="Enter style for font"
/>
</Form.Item>
)}
/>
<ErrorMessage component={SimpleError} name="style" />
<Field
type="text"
name="weight"
render={({ field }: FieldProps) => (
<Form.Item label="Weight">
<AutoComplete
{...field}
onChange={(value: SelectValue) => {
field.onChange({
target: { value, name: 'weight', id: 'weight' },
});
}}
dataSource={weights}
placeholder="Enter weight for font"
/>
</Form.Item>
)}
/>
<ErrorMessage component={SimpleError} name="weight" />
<Form.Item>
<Button
type="primary"
htmlType="submit"
className="login-form-button"
>
Upload
</Button>
</Form.Item>
</FormikForm>
)}
/>
);
};
export default FontUploadForm;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment