Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import { FormikProps } from 'formik';
- import { TextFieldProps } from '@mui/material';
- type ErrorKey = string;
- type ErrorMessage = string;
- export function setFormikProps<T>(
- fieldName: keyof T & string,
- { handleBlur, handleChange, touched, errors }: FormikProps<T>,
- errorMessageOverrides?: Record<ErrorKey, ErrorMessage>
- ): Partial<TextFieldProps> {
- const name = fieldName || 'name';
- let messageOverrides: string[] = [];
- if (errorMessageOverrides) {
- messageOverrides = Object.entries(errorMessageOverrides).reduce(
- (accumulatedErrors, [key, value]) => {
- const hasErrorValue = Boolean((errors as Record<string, string>)[key]);
- return hasErrorValue
- ? [...accumulatedErrors, value]
- : accumulatedErrors;
- },
- [] as string[]
- );
- }
- let textFieldProps: Partial<TextFieldProps> = {
- name,
- onBlur: handleBlur,
- onChange: handleChange,
- error: touched[fieldName] && Boolean(errors[fieldName]),
- helperText: touched[fieldName] && errors[fieldName],
- };
- if (messageOverrides.length > 0) {
- const joinedOverrides = messageOverrides.join('\n');
- textFieldProps = {
- ...textFieldProps,
- helperText: touched[fieldName] && errors[fieldName] && joinedOverrides,
- };
- }
- return textFieldProps;
- }
- export function getFormIsInvalid<T>({
- dirty,
- isValid,
- isSubmitting,
- }: FormikProps<T>): boolean {
- return !dirty || !isValid || isSubmitting;
- }
Advertisement
Add Comment
Please, Sign In to add comment