1
0

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.

分析屋が異世界転生してエンジニアになったAdvent Calendar 2022

Day 7

複数項目の入力値を配列でstate管理したい

Last updated at Posted at 2022-12-06

はじめに

グラフの描画などで複数の入力値を1つにまとめて管理したい状況があったので簡単にまとめてみます。

やりかた

①型を定義
②配列をstateで定義
③各項目をstateで定義
④各項目の入力値を配列に追加する

type Datas = {
  height: number;
  age: number;
};

export const Hoge = () => {
  const [datas, setDatas] = useState<Datas[]>([]);

  const [height, setHeight] = useState("");
  const [age, setAge] = useState("");

  const onClickButton = () => {
    if (height !== "" && age !== "") {
      setDatas([
        ...datas,
        {
          height: Number(height),
          age: Number(age),
        },
      ]);
    }
    setHeight("");
    setAge("");
  };
// onClickButtonの処理をどこかに追加する
return (<div>hoge</div>);
};


おわりに

データ管理の基本系は何も考えずに実装できるようになりたいです。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?