attilan

Formik props

Feb 14th, 2022
1,142
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import { FormikProps } from 'formik';
  2.  
  3. import { TextFieldProps } from '@mui/material';
  4.  
  5. type ErrorKey = string;
  6. type ErrorMessage = string;
  7.  
  8. export function setFormikProps<T>(
  9.   fieldName: keyof T & string,
  10.   { handleBlur, handleChange, touched, errors }: FormikProps<T>,
  11.   errorMessageOverrides?: Record<ErrorKey, ErrorMessage>
  12. ): Partial<TextFieldProps> {
  13.   const name = fieldName || 'name';
  14.  
  15.   let messageOverrides: string[] = [];
  16.  
  17.   if (errorMessageOverrides) {
  18.     messageOverrides = Object.entries(errorMessageOverrides).reduce(
  19.       (accumulatedErrors, [key, value]) => {
  20.         const hasErrorValue = Boolean((errors as Record<string, string>)[key]);
  21.  
  22.         return hasErrorValue
  23.           ? [...accumulatedErrors, value]
  24.           : accumulatedErrors;
  25.       },
  26.       [] as string[]
  27.     );
  28.   }
  29.  
  30.   let textFieldProps: Partial<TextFieldProps> = {
  31.     name,
  32.     onBlur: handleBlur,
  33.     onChange: handleChange,
  34.     error: touched[fieldName] && Boolean(errors[fieldName]),
  35.     helperText: touched[fieldName] && errors[fieldName],
  36.   };
  37.  
  38.   if (messageOverrides.length > 0) {
  39.     const joinedOverrides = messageOverrides.join('\n');
  40.     textFieldProps = {
  41.       ...textFieldProps,
  42.       helperText: touched[fieldName] && errors[fieldName] && joinedOverrides,
  43.     };
  44.   }
  45.  
  46.   return textFieldProps;
  47. }
  48.  
  49. export function getFormIsInvalid<T>({
  50.   dirty,
  51.   isValid,
  52.   isSubmitting,
  53. }: FormikProps<T>): boolean {
  54.   return !dirty || !isValid || isSubmitting;
  55. }
  56.  
Advertisement
Add Comment
Please, Sign In to add comment