admin管理员组

文章数量:1399180

How can I pass custom props to the inputComponent?

For example, I have a MuiTextField ponent:

const CustomerSocialMask = React.forwardRef<HTMLElement, CustomProps>(
  function CustomerSocialMask(props, ref: any) {
    // deploy test
    const { onChange, ...other } = props;
    return (
      <IMaskInput
        {...other}
        mask="000.000.000-00"
        definitions={{
          '#': /[1-9]/,
        }}
        inputRef={ref}
        onAccept={(value: any) =>
          onChange({ target: { name: props.name, value } })
        }
        overwrite={false}
      />
    );
  },
);

<MuiTextField
  sx={{
    '& input[type=number]': {
      MozAppearance: 'textfield',
    },
    '& input[type=number]::-webkit-outer-spin-button': {
      WebkitAppearance: 'none',
      margin: 0,
    },
    '& input[type=number]::-webkit-inner-spin-button': {
      WebkitAppearance: 'none',
      margin: 0,
    },
  }}
  variant="standard"
  multiline={data.fieldType === FieldType.LONG_TEXT}
  placeholder={data.settings.placeholder}
  fullWidth
  type={inputType}
  InputProps={{
    startAdornment: prefix && (
      <InputAdornment position="start">
        <Typography color="text.primary">{prefix}</Typography>
      </InputAdornment>
    ),
    endAdornment: suffix && (
      <InputAdornment position="start">
        <Typography color="text.primary">{suffix}</Typography>
      </InputAdornment>
    ),
    inputComponent: CustomerSocialMask,
  }}
  name={name}
  onChange={
    (data.settings as ShortTextSettings).valueType ===
      ValueType.CURRENCY || path === PersonalDetail.PHONE
      ? onChange
      : handleChange
  }
  onBlur={handleBlurWithFix}
  value={valueAdjusted}
  error={!!error}
  helperText={error}
/>

When I try to pass custom props to the inputComponent like:

inputComponent: <CustomerSocialMask customProp={something}/>,

I get the following error:

Failed prop type: Invalid prop `inputComponent` of type `object` supplied to `ForwardRef(Input2)`, expected a single ReactElement type.

So I must only provide refs to the inputComponent, but I can't pass external data / props to the forwardRef ponent. I want to use a customProp inside the CustomerSocialMask ponent por example. How would I do that? Couldn't find anything on the docs.

How can I pass custom props to the inputComponent?

For example, I have a MuiTextField ponent:

const CustomerSocialMask = React.forwardRef<HTMLElement, CustomProps>(
  function CustomerSocialMask(props, ref: any) {
    // deploy test
    const { onChange, ...other } = props;
    return (
      <IMaskInput
        {...other}
        mask="000.000.000-00"
        definitions={{
          '#': /[1-9]/,
        }}
        inputRef={ref}
        onAccept={(value: any) =>
          onChange({ target: { name: props.name, value } })
        }
        overwrite={false}
      />
    );
  },
);

<MuiTextField
  sx={{
    '& input[type=number]': {
      MozAppearance: 'textfield',
    },
    '& input[type=number]::-webkit-outer-spin-button': {
      WebkitAppearance: 'none',
      margin: 0,
    },
    '& input[type=number]::-webkit-inner-spin-button': {
      WebkitAppearance: 'none',
      margin: 0,
    },
  }}
  variant="standard"
  multiline={data.fieldType === FieldType.LONG_TEXT}
  placeholder={data.settings.placeholder}
  fullWidth
  type={inputType}
  InputProps={{
    startAdornment: prefix && (
      <InputAdornment position="start">
        <Typography color="text.primary">{prefix}</Typography>
      </InputAdornment>
    ),
    endAdornment: suffix && (
      <InputAdornment position="start">
        <Typography color="text.primary">{suffix}</Typography>
      </InputAdornment>
    ),
    inputComponent: CustomerSocialMask,
  }}
  name={name}
  onChange={
    (data.settings as ShortTextSettings).valueType ===
      ValueType.CURRENCY || path === PersonalDetail.PHONE
      ? onChange
      : handleChange
  }
  onBlur={handleBlurWithFix}
  value={valueAdjusted}
  error={!!error}
  helperText={error}
/>

When I try to pass custom props to the inputComponent like:

inputComponent: <CustomerSocialMask customProp={something}/>,

I get the following error:

Failed prop type: Invalid prop `inputComponent` of type `object` supplied to `ForwardRef(Input2)`, expected a single ReactElement type.

So I must only provide refs to the inputComponent, but I can't pass external data / props to the forwardRef ponent. I want to use a customProp inside the CustomerSocialMask ponent por example. How would I do that? Couldn't find anything on the docs.

Share Improve this question asked Aug 26, 2022 at 0:37 Ericson WilliansEricson Willians 7,85515 gold badges67 silver badges124 bronze badges 3
  • 3 Is this not what the inputProps attribute is for (the lower case 'i' attribute not the upper case InputProps)? You are replacing the default input ponent and the ponent is passed all MUI calculated props + all user defined props from inputProps. – Jacob Smit Commented Aug 29, 2022 at 4:40
  • Turns out you were right, if I pass some arbitrary prop to lowercase inputProps I can access it inside the inputComponent in uppercase InputProps. Thank you very much sir! That wasn't obvious at all. – Ericson Willians Commented Aug 29, 2022 at 11:29
  • @JacobSmit you can post it as an answer to get the bounty. – Nice Books Commented Sep 3, 2022 at 18:09
Add a ment  | 

3 Answers 3

Reset to default 5

Material UI TextField provides a few 'Props' style attributes to apply configuration to the child ponents that are bined to make the input.

Two of note are:

  • InputProps: This provides properties to the Material UI ponent that is selected based on the variant property i.e. OutlinedInput, FilledInput, etc.
  • inputProps: This provides properties to the underlying input which is being used, by default this is an input.

When using InputProps.inputComponent the underlying input is replaced with the provided ponent, this allows you to use inputProps to pass extra properties to configure the custom input.

Example:

<TextField
    InputProps={{
        inputComponent: CustomerSocialMask,
    }}
    inputProps={{
        customProp: something
    }}
/>

The solution seems to be very close to what you are doing, you just need to pass a function to inputComponent.

inputComponent: (props) => <CustomerSocialMask {...props} myCustomPropName={doSomething} />

Hello MUITextfield inputProps attribute can accept only the types with a normal input tag can accept (varies depending on the type), however you can use the MUI Input ponent to pass with custom ponent to use, and there the inputProps is available so you can pass the props of your custom field.

I created a quick draft in this Sandbox: https://codesandbox.io/s/react-mui-using-a-custom-ponent-with-input-pnent-zysvji?file=/src/App.tsx

I hope this helps. E

本文标签: