-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathFieldError.ts
84 lines (73 loc) · 2.14 KB
/
FieldError.ts
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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
import { ComponentProps, ComponentType, createElement, FC, forwardRef, ReactElement } from 'react';
import { useError, useParentField } from '../hooks';
export interface FieldErrorRendererProps {
error: string | undefined | { [key: string]: any };
}
export interface FieldErrorRenderer {
(props: FieldErrorRendererProps): ReactElement | null;
}
export interface FieldErrorProps {
children?: FieldErrorRenderer;
/**
* Defaults to "" means that it looks for root errors on field
* In case of Object/Array/Form it means that the error for this field only will be rendered
* And not for nested fields
*/
name?: string;
}
interface FieldErrorComponent {
<TAs extends keyof JSX.IntrinsicElements = any>(
props: { as: TAs } & JSX.IntrinsicElements[TAs] & FieldErrorProps,
): ReactElement | null;
<TAs extends ComponentType<{ error: string | undefined | { [key: string]: any } }> = FC<{}>>(
props: { as: TAs } & ComponentProps<TAs> & FieldErrorProps,
): ReactElement | null;
(props: FieldErrorProps): ReactElement | null;
displayName?: string;
}
export const FieldError: FieldErrorComponent = forwardRef(
(
{
as,
children,
name = '',
...restProps
}: {
as?:
| keyof JSX.IntrinsicElements
| ComponentType<{ error: string | undefined | { [key: string]: any } }>;
} & FieldErrorProps,
ref: any,
) => {
const [parentField] = useParentField();
const error = useError(name, parentField);
if (typeof as === 'string') {
if (typeof children !== 'function') {
throw new Error('Children renderer must be provided');
}
return createElement(
as,
{
...restProps,
ref,
},
children({ error }),
);
}
if (as != null) {
return createElement(
as,
{
...restProps,
ref,
} as any,
typeof children === 'function' ? children({ error }) : null,
);
}
if (typeof children !== 'function') {
throw new Error('Chilren renderer must be provided');
}
return children({ error });
},
);
FieldError.displayName = 'FieldError';