on master help sign in
bridge/src/form/BridgeForm.tsx
70 lines 2.0 kB history raw
1import React, { useCallback } from 'react';
2import { Form, FormRenderProps } from 'react-final-form';
3import arrayMutators from 'final-form-arrays';
4import { noop } from 'lodash';
6import ValuesHandler from './ValuesHandler';
7import ValidationPauser from './ValidationPauser';
8import { CSSProperties } from 'styled-components';
9import { FormState } from 'final-form';
11/**
12 * BridgeForm adds nice-to-haves for every form in bridge.
13 * + afterSubmit callback for redirects
14 * + default onSubmit to noop so react-final-form doesn't throw
15 * + pauses validation when the form is unmounted
16 * + `onValues` handler for reactive changes
17 * + automatically includes array and field data mutators
18 */
19interface BridgeFormProps {
20 // children: React.ReactNode;
21 children?: any;
22 // onValues?: (values: { [k: string]: string }, valid: boolean, form: any) => void | typeof noop;
23 onValues?: any;
24 // onSubmit?: (values: { [k: string]: string }) => void | typeof noop;
25 onSubmit?: any;
26 validate?: any;
27 initialValues?: any;
28 style?: any;
29 className?: string;
30 afterSubmit?: VoidFunction;
31 rest?: React.HTMLProps<HTMLFormElement>;
34export default function BridgeForm({
35 children,
36 onValues,
37 onSubmit = noop,
38 afterSubmit = noop,
39 ...rest
40}: BridgeFormProps) {
41 const _onSubmit = useCallback(
42 async (...args) => {
43 const errors = await onSubmit(...args);
44 if (errors) {
45 return errors;
46 }
48 afterSubmit();
49 },
50 [afterSubmit, onSubmit]
51 );
53 return (
54 <Form mutators={{ ...arrayMutators }} onSubmit={_onSubmit} {...rest}>
55 {(
56 formProps: FormRenderProps<any, Partial<any>> & {
57 style: CSSProperties;
58 } & FormState<any>
59 ) => (
60 <form
61 style={formProps?.style || { display: 'contents' }}
62 onSubmit={formProps.handleSubmit}>
63 <ValidationPauser />
64 {children(formProps)}
65 {onValues && <ValuesHandler {...formProps} onValues={onValues} />}
66 </form>
67 )}
68 </Form>
69 );