LoginSignup
0
0

More than 1 year has passed since last update.

【React/TypeScript】useState()で入力項目を管理する。

Last updated at Posted at 2023-02-04

はじめに

昨今、react-hook-formなど入力値を取得〜バリデーションまでしてくれるライブラリが充実していますが、今回、useState()で入力フォームのStateを管理する方法を書きたいと思います。(自分へのメモも兼ねて)
また、この記事は、useState()の知識があることを前提に記事が書かれています。
useStateに関する詳細は、公式を一読ください。

サンプルコード

以下のようなログインフォームがあるとします。
uiはMaterialUIを使用しています。(*公式ドキュメントはこちら)

type Props = {
    name: string;
    password: string;
};

const nullLoginParam: Props = {
  name: '',
  password: '',
};

const Login = () => {
  const [params, setParams] = useState<Props>(nullLoginParam);
  const onClickLogin = () => { 
    // ログイン処理
  }
  return(
    <Box>
        <TextField
          id="name"
          label="ユーザー名"
          name="name"
        />
        <TextField
          id="password"
          label="パスワード"
          name="password"
        />
        <LoadingButton onClick={onClickLogin}>
          ログイン
        </LoadingButton>
    </Box>
  );
};

実装

それでは、TextFieldのonChangeイベントハンドラにonChangeState()関数を指定して、管理していきます。

/* 省略 */

const Login = () => {
  const [params, setParams] = useState<Props>(nullLoginParam);
+ const onChangeState = (
+   e: React.ChangeEvent<HTMLTextAreaElement | HTMLInputElement>
+ ) => {
+   const { value, name: key } = e.target;
+   setParams({ ...params, [key]: value });
+ } 
  const onClickLogin = () => {
    // ログイン処理
  }
  return(
    <Box>
        <TextField
          id="name"
          label="ユーザー名"
          name="name"
+         onChange={onChangeState}
        />
        <TextField
          id="password"
          label="パスワード"
          name="password"
+         onChange={onChangeState}
        />
        <LoadingButton onClick={onClickLogin}>
          ログイン
        </LoadingButton>
    </Box>
  );
};

onChangeStateは、onChangeイベントハンドラからのイベント(e)を受け取ります。
このeの中にあるtargetには、入力フォームに入力された値(value)や<TextField>name=の値が入っているので、

+ const { value, name: key } = e.target;

と、分割代入で取り出します。(name: keyは、keyという変数にnameを代入しています。)


次に、setParamsの中にparamsをスプレット構文で展開し、値を入れていきます。

+   setParams({ ...params, [key]: value }); // ...params, password: '1234' のように値がセットされます。

以上が、useStateで入力フォームのStateを管理する方法でした。

参考にした記事

0
0
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
0
0