-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathArrayField.tsx
61 lines (55 loc) · 1.68 KB
/
ArrayField.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
import React, {
ComponentProps,
ComponentType,
Dispatch,
FC,
Fragment,
ReactElement,
ReactNode,
forwardRef,
} from 'react';
import { ArrayFieldAction, ArrayFieldState } from '../reducers';
import { CompositeFieldContext, useArrayField } from '../hooks';
export interface ArrayFieldRenderer<TValue extends any[]> {
(
state: ArrayFieldState<TValue>,
dispatch: Dispatch<ArrayFieldAction<TValue>>,
): ReactElement | null;
}
export interface ArrayFieldProps<TValue extends any[]> {
children?: ArrayFieldRenderer<TValue> | ReactNode;
name: string | number;
removeOnUnmount?: boolean;
}
interface ArrayFieldComponent {
<TValue extends any[] = any[]>(props: ArrayFieldProps<TValue>): ReactElement | null;
<TValue extends any[] = any[], TAs extends keyof JSX.IntrinsicElements = any>(
props: { as: TAs } & JSX.IntrinsicElements[TAs] & ArrayFieldProps<TValue>,
): ReactElement | null;
<TValue extends any[] = any[], TAs extends ComponentType<any> = FC<{}>>(
props: { as: TAs } & ComponentProps<TAs> & ArrayFieldProps<TValue>,
): ReactElement | null;
displayName?: string;
}
export const ArrayField: ArrayFieldComponent = forwardRef(
(
{
as: As = Fragment,
children,
name,
removeOnUnmount,
...restProps
}: ArrayFieldProps<any[]> & { as: any },
ref,
) => {
const state = useArrayField<any[]>(name, removeOnUnmount);
return (
<CompositeFieldContext.Provider value={state}>
<As ref={ref} {...restProps}>
{typeof children === 'function' ? children(state[0], state[1]) : children}
</As>
</CompositeFieldContext.Provider>
);
},
) as any;
ArrayField.displayName = 'ArrayField';