Exploring My Implementation
I have devised a function that takes an argument to access specific formik errors dynamically. This requires using bracket notation instead of dot notation as shown below:
import {useFormikContext} from 'formik';
function TextField(name: string): JSX.Element {
const {errors} = useFormikContext();
console.log(errors[name]); // TypeScript error occurs here
// other function/component code
}
The Challenge at Hand
Although the code functions properly and retrieves errors based on the passed name as a string, I am encountering TypeScript errors:
errors[name]: TS7053: Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'FormikErrors<unknown>'. No index signature with a parameter of type 'string' was found on type 'FormikErrors<unknown>'.
My Desired Outcome
While I have reviewed the types provided by formik, I am struggling to create a function that accepts the error name as an argument without raising TypeScript complaints.
Revised Approach
Our current issue: attempting to retrieve errors dynamically using bracket notation. How can we incorporate FormData
in this scenario?
import {getIn, useFormikContext} from 'formik';
import React from 'react';
import {Input as UIKInput} from '@ui-kitten/components';
import {InputProps as UIKInputProps} from '@ui-kitten/components/ui/input/input.component';
export type TextFieldProps = UIKInputProps & {
name: string;
};
export default function TextField(props: TextFieldProps): JSX.Element {
const {name, ...inputProps} = props;
const {setFieldTouched, handleChange, errors, touched} = useFormikContext();
return (
<UIKInput
status={errors[name] && touched[name] ? 'danger' : 'basic'}
caption={
errors[name] && touched[name] ? errors[name] : ''
}
onBlur={() => setFieldTouched(name)}
onChangeText={handleChange(name)}
{...inputProps}
/>
);
}
Further Refinement
Utilizing getIn
to access specific errors or touched states while avoiding type errors.
import {getIn, useFormikContext} from 'formik';
import React from 'react';
import {Input as UIKInput} from '@ui-kitten/components';
import {InputProps as UIKInputProps} from '@ui-kitten/components/ui/input/input.component';
export type TextFieldProps = UIKInputProps & {
name: string;
};
export default function TextField(props: TextFieldProps): JSX.Element {
const {name, ...inputProps} = props;
const {setFieldTouched, handleChange, errors, touched} = useFormikContext();
return (
<UIKInput
status={getIn(errors, name) && getIn(touched, name) ? 'danger' : 'basic'}
caption={
getIn(errors, name) && getIn(touched, name) ? getIn(errors, name) : ''
}
onBlur={() => setFieldTouched(name)}
onChangeText={handleChange(name)}
{...inputProps}
/>
);
}