so um I’ve been trying to make a reusable Input component so I don’t have to copy paste all of the styles everywhere and I made this
import { FieldValues, UseFormRegister, Path } from ‘react-hook-form’;
interface Props<T extends FieldValues> {
label: string;
id: keyof T;
type?: string;
register: UseFormRegister<T>;
error?: string;
}
const FormField = <T extends FieldValues>({
label,
id,
type = 'text',
register,
error,
}: Props<T>) => {
return (
<div className='flex flex-col gap-4 border p-2'>
<label className='font-bold' htmlFor={id as string}>
{label}
</label>
<input type={type} id={id as string} {...register(id as Path<T>)} />
{error && <span className='text-red-500'>{error}</span>}
</div>
);
};
export default FormField;
But I feel like this is not the right way to do it or maybe it is at this point I don’t know. if anyone has built a similar component I would appreciate help and suggestion
2
Answers
you should try adding more flexibility by accepting additional props that you can spread onto the input element, such as
className
,placeholder
,disabled
, etc., to customize the input further and try adding additional styling or accessibility features to make errors more noticeable to users, such as changing the input border color or adding anaria
role.you can also add comments to explain each prop and its purpose and examples of how to use the component.
Since you already know you’ll be using
react-hook-form
to implement your reusable input, you can make it an internal dependency with useFormContext; this way there’s less data to pass with props.You can also add type-safety to your
Props.type
field.Updated code below: