2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Material-uiでカウンター付きTextField

Last updated at Posted at 2021-04-26

material-uiでカウンターがサポートされてない

マテリアルデザインのスペックでは、テキストフィールドにカウンターもありますが、material-uiにはカウンターのAPIが実装されていません。

ということで何回かカスタムコンポーネントを書くことになったので、メモとして残します。

TextFieldをラップする

maxLengthプロップを持たせたカスタムコンポーネントを作成します。

type AdditionalTextFieldProps = {
  maxLength?: number;
};

type CustomTextFieldProps = TextFieldProps & AdditionalTextFieldProps;

const CustomTextField: React.FC<CustomTextFieldProps> = ({
  maxLength,
  inputProps,
  helperText,
  ...rest
}) => {
  const inputRef = useRef<HTMLInputElement>(null);
  const currentValueLength = inputRef.current?.value?.length;
  const isCounterAvailable =
    maxLength && typeof currentValueLength === 'number';

  return (
    <TextField
      inputRef={inputRef}
      inputProps={{...inputProps, maxLength}}
      helperText={
        (helperText || isCounterAvailable) && (
          <Box component="span" display="flex" justifyContent="space-between">
            <Typography variant="caption" color="textSecondary">
              {helperText || ''}
            </Typography>
            {isCounterAvailable && (
              <Typography variant="caption" color="textSecondary">
                {currentValueLength}/{maxLength}
              </Typography>
            )}
          </Box>
        )
      }
      {...rest}
    />
  );
};

その他

FormHelperTextPropscomponentがタイプ定義されてないみたいです。

2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?