-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathObjectField.tsx
69 lines (63 loc) · 1.88 KB
/
ObjectField.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
62
63
64
65
66
67
68
69
import React, {
ComponentProps,
ComponentType,
Dispatch,
FC,
Fragment,
ReactElement,
ReactNode,
forwardRef,
} from 'react';
import { ObjectFieldState, ObjectFieldAction } from '../reducers';
import { CompositeFieldContext, useObjectField } from '../hooks';
export interface ObjectFieldRenderer<TValue extends { [key: string]: any }> {
(
state: ObjectFieldState<TValue>,
dispatch: Dispatch<ObjectFieldAction<TValue>>,
): ReactElement | null;
}
export interface ObjectFieldProps<TValue extends { [key: string]: any }> {
children?: ObjectFieldRenderer<TValue> | ReactNode;
name: string;
removeOnUnmount?: boolean;
}
interface ObjectFieldComponent {
<TValue extends { [key: string]: any } = { [key: string]: any }>(
props: ObjectFieldProps<TValue>,
): ReactElement | null;
<
TValue extends { [key: string]: any } = { [key: string]: any },
TAs extends keyof JSX.IntrinsicElements = any
>(
props: { as: TAs } & JSX.IntrinsicElements[TAs] & ObjectFieldProps<TValue>,
): ReactElement | null;
<
TValue extends { [key: string]: any } = { [key: string]: any },
TAs extends ComponentType<any> = FC<{}>
>(
props: { as: TAs } & ComponentProps<TAs> & ObjectFieldProps<TValue>,
): ReactElement | null;
displayName?: string;
}
export const ObjectField: ObjectFieldComponent = forwardRef(
(
{
as: As = Fragment,
children,
name,
removeOnUnmount,
...restProps
}: ObjectFieldProps<{ [key: string]: any }> & { as: any },
ref,
) => {
const state = useObjectField<{ [key: string]: 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;
ObjectField.displayName = 'ObjectField';