4
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 1 year has passed since last update.

React Mui-Materialの数値入力フィールドを使いやすく

Posted at

Mui-Materialの Textfield ですが type="number" を指定すれば、数値入力用の入力欄が作れます。ただ、これだけだとちょっと使いづらいです

  • 入力時の先頭へゼロが残ってしまうことがある
  • マウス操作で誤って入力値をユーザーが変更してしまうことがある
  • ブラウザによって挙動が違う

これを解消するべく、以下のようなコンポーネントを作りました。
使えそうなシーンがあれば使ってみてね

NumericField.tsx
import TextField from "@mui/material/TextField/TextField";
import { CSSProperties } from "react";

type P = {
  state: string;
  setState: React.Dispatch<React.SetStateAction<string>>,
  label?: string;
  style?: CSSProperties;
  required?: boolean;
  fullWidth?: boolean;
};

export function NumericField(props: P) {

  const onChangeHandle = (e: React.ChangeEvent<HTMLTextAreaElement | HTMLInputElement>) => {
    const result = Math.abs(Number(e.target.value)).toString();

    if (result === "NaN") {
      props.setState("");
    } else {
      props.setState(result);
    }
  };

  return <TextField
    fullWidth={props.fullWidth}
    required={props.required}
    value={props.state}
    onChange={onChangeHandle}
    label={props.label}
    style={props.style}
    inputProps={{
      inputMode: "numeric",
      pattern: "[0-9]*"
    }}
  />;
}
4
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
4
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?