React Ant Design Dynamic Graphql Form Using Typescript : Part (1/3)
19th Mar 2019
This is an advanced typescript tutorial for react development.
Scenario
Often we encounter situations where we have to write the basic forms (register, login, newsletter,etc..) and submit them for graphql mutations. It's a tiresome task to do it for all the forms in your project. To tackle such situation we can create a dynamic form generator with full static type support and custom validation handler.
1. Define the interfaces
Create a file called interface.ts
and add the following interfaces.
1.1 Form Field
IFormField<TVariables>
provides the definition for all individual field items. Where TVariables
are the form element ids (check the final example)
import { GetFieldDecoratorOptions, WrappedFormUtils } from 'antd/lib/form/Form'
export interface IFormField<TVariables> extends FormItemProps {
key?: string
decoratorOption: GetFieldDecoratorOptions
componentProps: InputProps
customValidator?: (
form: WrappedFormUtils<TVariables>,
value: any,
callback: (err?: string) => void
) => void
}
1.2 Form Items
IFormItems<TVariables>
contains all the field definitions for given variable keys.
export type IFormItems<TVariables> = {
[T in keyof TVariables]: IFormField<TVariables>
}
1.3 Base props
IGenericFormBaseProps<TVariables, TData>
is the base interface for form component. Base interface provides all the necessary component props except the props from antd FormComponentProps<TVariables>
interface. TData
is the result interface of graphql mutation.
export interface IGenericFormBaseProps<TVariables, TData> {
submitBtnLabel: string
fields: IFormItems<TVariables>
fieldOrder: Array<keyof TVariables>
transformValues?: (values: TVariables) => any
loadingMessage: string
mutationSchema: string
onSuccess?: (data: TData) => void
}
1.4 Form Props
This is our final interface. This extends from IGenericFormBaseProps<TVariables, TData>
& ormComponentProps<TVariables>
export interface IGenericFormProps<TVariables, TData>
extends IGenericFormBaseProps<TVariables, TData>,
FormComponentProps<TVariables> {}