|
1 |
| -import React, { HTMLAttributes } from "react"; |
2 |
| -import { DefaultError, FormState } from "../form"; |
| 1 | +import React from "react"; |
| 2 | +import { DefaultError, DefaultState, FormState } from "../form"; |
3 | 3 | import { useListener } from "../hooks";
|
| 4 | +import { ElementProps } from "./Field"; |
4 | 5 |
|
5 |
| -export type FormErrorProps<T extends object, K extends keyof T, Error extends string = DefaultError> = Omit< |
6 |
| - HTMLAttributes<HTMLParagraphElement>, |
7 |
| - "name" | "form" |
8 |
| -> & { |
9 |
| - form: FormState<T, any, Error>; |
10 |
| - name: K; |
11 |
| -}; |
12 |
| - |
13 |
| -/** |
14 |
| - * The builtin form error. You must always specify **form** and **name**. |
15 |
| - * |
16 |
| - * **FormInput**, **FormTextArea** and **FormSelect** are also available. |
17 |
| - * |
18 |
| - * Because this component is very basic, it is recommended to [implement your own error component](https://codestix.github.io/typed-react-form/reference/FormError#custom-error-component). |
19 |
| - */ |
20 |
| -export function FormError<T extends object, K extends keyof T, Error extends string = DefaultError>({ |
21 |
| - form, |
22 |
| - name, |
23 |
| - ...rest |
24 |
| -}: FormErrorProps<T, K, Error>) { |
25 |
| - const { error } = useListener(form, name); |
| 6 | +export function FieldError< |
| 7 | + T extends object, |
| 8 | + K extends keyof T, |
| 9 | + C extends React.FunctionComponent<any> | keyof JSX.IntrinsicElements, |
| 10 | + Error extends string = DefaultError, |
| 11 | + State = DefaultState |
| 12 | +>( |
| 13 | + props: { |
| 14 | + form: FormState<T, State, Error>; |
| 15 | + name: K; |
| 16 | + component?: C; |
| 17 | + transformer?: (error: Error) => React.ReactNode; |
| 18 | + } & Omit<ElementProps<C>, "transformer" | "component" | "name" | "form"> |
| 19 | +) { |
| 20 | + const { form, component = React.Fragment, transformer } = props; |
| 21 | + const { error } = useListener(form, props.name); |
26 | 22 | if (!error || typeof error === "object") return null;
|
27 |
| - return <p {...rest}>{error + ""}</p>; |
| 23 | + return React.createElement(component, { children: String(transformer ? transformer(error as Error) : error) }); |
28 | 24 | }
|
0 commit comments