Skip to content

Instantly share code, notes, and snippets.

@paulm17
Created July 5, 2022 12:45
Show Gist options
  • Save paulm17/4b5a0f535f6912beb482dad3ff07a757 to your computer and use it in GitHub Desktop.
Save paulm17/4b5a0f535f6912beb482dad3ff07a757 to your computer and use it in GitHub Desktop.
Controller + Default Values example
<Form
inputComponent={FormInput}
buttonComponent={FormButton}
schema={props.schema as any}
defaultValues={props.initialValues}
onSubmit={async (values) => {
...
}
{({ Field, Errors, Button, control, formState, register, watch }) => (
<>
<Card.Section p="md">
<div className="mb-4 block text-sm font-medium text-gray-600 dark:text-gray-200">
<Field name="categoryId">
{({ Label, Errors, name }) => (
<>
<Group position="left" className="!items-baseline">
<Label className="w-1/6">Category</Label>
<Stack align="flex-start" className="!flex-grow">
<CategoryDropDown
control={control}
formState={formState}
name={name as string}
/>
<Errors className="-mt-1 text-xs text-red-600" />
</Stack>
</Group>
</>
)}
</Field>
</div>
<Errors />
</Card.Section>
</>
)}
</Form>
interface categoryDropDownProps {
control: Control<any, any>
formState: FormState<any>
name: string
}
function CategoryDropDown({ control, formState, name }: categoryDropDownProps) {
const query = getData...
const options = useMemo(() => {
const data: { value: string; label: string }[] = [{ value: "-1", label: "Select" }]
if (query !== undefined) {
query.forEach((category) => {
data.push({ value: category.id, label: category.name })
})
}
return data
}, [query])
return (
<Controller
control={control}
name={name}
render={({ field: { onChange, value, ref } }) => (
<FormSelect
className="w-full"
data={options}
placeholder="Select a Category"
value={value}
onChange={onChange}
ref={ref}
></FormSelect>
)}
/>
)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment