'Formik useField hook doesn't pass name or label props?
My goal really isn't too complex, I need custom behaviour for the form fields (input, select and date) onBlur().
Am starting off with the input because the select and datepicker components have additional requirements and will likely be packages.
According to the docs I should be able to create a custom component and use it with <Field as /> or <Field component /> neither of which work the way I expect (or hope).
Seems like I'm missing something extremely basic, but I map over the data which has a structure like this:
interface CaseSummaryFiltersInterface {
order: number;
name: string;
testid: string;
label: string;
// ...superfluous stuff...
}
// Part of Form component
{filters?.map((filter, filterIndex) => {
return <Field name={filter.name} component={CustomInput} />;
})}
// CustomInput.tsx
type CustomInputProps = {
name: string;
label: string;
type?: 'InputType';
className?: string;
} & Omit<DetailedHTMLProps<InputHTMLAttributes<HTMLInputElement>, HTMLInputElement>, 'size'>;
export const CustomInput: FC<CustomInputProps> = props => {
const [field] = useField({
name: props.name,
});
console.log(props.name); // undefined
console.log(field); // {name: undefined, values: {...thingsIneed} }
const handleUpdate = (e: ChangeEvent<HTMLInputElement>) => {
// things I need to do
};
return (
<div data-testid="form-control">
<input
type="text"
{...field}
className={FormStyles.formInput}
onBlur={handleUpdate}
name={props.name}
/>
</div>
);
};
If I just use <Field /> on it's own then I have access to everything I need but none of the functionality that is required. Any suggestions?
Solution 1:[1]
You are mixing the component prop and the useField hook.
If you want to use the component prop, your CustomInput component will receive the props field and form. To access the field name you have to use props.field.name not props.name
If you want to use the useField hook, you dont need to use <Field /> at all.
Just use <CustomInput name="name" />
More info at https://formik.org/docs/api/field#component and https://formik.org/docs/api/useField
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Silvino Escalona |
