Home > Blockchain >  How to conditional use props in a TextField MUI component
How to conditional use props in a TextField MUI component

Time:02-06

I want to create a general component based on MUI TextField in conjunction with Formik

I have already handle the rest of the props, but I don't know how to do it with value and onChange

  <Field
   disabled={isDisabled}
   as={TextFieldStyled}
   sx={signUpFormTextField}
   label={inputLabel}
   name={inputName}
   helperText={
    <ErrorMessage name={inputName}>
     {(msg) => (
      <Typography component="span" sx={errorMessage}>
         {msg}
      </Typography>
     )}
    </ErrorMessage>
   }
   error={hasError}

   // ------------------------
   onChange={
     customOnChangeMethod ? customOnChangeMethod : defaultOnChangeMethod
   }
   value={
     customValue ? customValue : use default value
   }
   // ------------------------
  />

CodePudding user response:

You can do something like this:

function MyFormField(
  isDisabled,
  inputLabel,
  inputName,
  hasError,
  onChange,
  customOnChange = null,
  value,
  customValue = null
  //otherProps
) {
  return (
    <TextField
      disabled={isDisabled}
      label={inputLabel}
      name={inputName}
      error={hasError}
      //other props
      onChange={customOnChange || onChange}
      value={customValue || value}
    />
  );
}

So customValue and customOnChange are optional and are null by default. They will be used only when you put them in the component props.

<MyFormField
  // these are common between all your form fields:
  value={value}
  onChange={handleChange}
  //these you can put wherever you like and will override the previous ones:
  customValue={customValue}
  customOnChange={handleCustomChange}
  //...other props
/>
  • Related