Skip to content

Instantly share code, notes, and snippets.

@iRoachie
Created June 20, 2022 10:32
Show Gist options
  • Save iRoachie/b04aa7dc4426f11d264142f7a3cb0d78 to your computer and use it in GitHub Desktop.
Save iRoachie/b04aa7dc4426f11d264142f7a3cb0d78 to your computer and use it in GitHub Desktop.
Hook form usage
import {
FormControl,
FormLabel,
Input,
FormErrorMessage,
FormHelperText,
} from '@chakra-ui/react';
import classNames from 'classnames';
import { useController } from 'react-hook-form';
import type { InputProps, Select, Textarea } from '@chakra-ui/react';
interface FormInputProps extends InputProps {
className?: string;
label?: string;
name: string;
as?: typeof Input | typeof Select | typeof Textarea;
helperText?: string;
}
/**
* Input component that hooks up to React Hook Form.
*/
export const HookFormInput: React.FC<FormInputProps> = ({
className,
label,
as: As = Input,
helperText,
isRequired,
name,
...props
}) => {
const { field, formState, fieldState } = useController({ name });
const containerClasses = classNames({
[className!]: !!className,
});
return (
<FormControl
className={containerClasses}
isInvalid={Boolean(fieldState.error)}
isRequired={isRequired}
>
{label && (
<FormLabel htmlFor={field.name} fontSize={props.size}>
{label}
</FormLabel>
)}
{/* @ts-ignore */}
<As
id={field.name}
{...field}
{...props}
onChange={(e) => {
props.onChange?.(e as any);
field.onChange(e);
}}
isDisabled={formState.isSubmitting}
/>
{helperText && <FormHelperText>{helperText}</FormHelperText>}
<FormErrorMessage>{fieldState.error?.message}</FormErrorMessage>
</FormControl>
);
};
export const Example = () => {
const methods = useForm<InferType<typeof schema>>({
resolver: yupResolver(schema),
defaultValues: {
name: '',
email: '',
},
});
const onSubmit = methods.handleSubmit(async (values) => {});
return (
<FormProvider {...methods}>
<form onSubmit={onSubmit}>
<HookFormInput name="name" label="Name" className="mb-6" />
<HookFormInput name="email" label="Email Address" />
<Button
type="submit"
colorScheme="accent"
isLoading={methods.formState.isSubmitting}
>
Create
</Button>
</form>
</FormProvider>
);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment