LoginSignup
23
9

More than 1 year has passed since last update.

【React Hook Form】useFieldArrayを試してみた

Last updated at Posted at 2021-08-14

React Hook Form

React Hook Form をちゃんと使いこなしたいなぁと思っているので、これから少しずつ試して行こうと思っています( React Hook Formシリーズ化決意🤓 )。

  • React Hook Form の基本
    • React Hook Form の基本機能
  • React Hook Form の応用
    • useForm
    • useController
    • useFormContext
    • useWatch
    • useFormState
    • useFieldArray  <=いまココ
      • useFieldArrayがネストされた場合編

React Hook Form で料金計算フォームを作ってみた

請求書とか見積書、納品書などでよく見かける、行を追加削除出来る超単純なフォームを作ってみました。

お気に入りのコンポーネントライブラリ「Chakra UI」との組み合わせですが一部 React Hook Form と相性の悪い Form 系のコンポーネントもあるみたいです。ちなみに Number Inputをうまく組み込むことが出来なかったので解決したい。。。

useFieldArrayで請求書テーブル

コードは次の通りです。

App.tsx
import {
  Box,
  Flex,
  Button,
  Table,
  Thead,
  Tbody,
  Tr,
  Th,
  Td,
  IconButton,
  Text,
  Input
} from "@chakra-ui/react";
// Chakra icons を import
import { DeleteIcon, AddIcon } from "@chakra-ui/icons";
// React Hook Form を import
import { useForm, useFieldArray, useWatch, Control } from "react-hook-form";

// FormValues の型
type FormValues = {
  itemRows: {
    itemName: string;
    unitPrice: number;
    quantity: number;
    amount: number;
    taxAmount: number;
  }[];
};

// すべてのアイテムの金額を合計する TotalAmount コンポーネント
const TotalAmount = ({ control }: { control: Control<FormValues> }) => {
  const formValues = useWatch({
    name: "itemRows",
    control
  });
  const total = formValues.reduce(
    (acc, { unitPrice, quantity }) => acc + (unitPrice || 0) * (quantity || 0),
    0
  );
  return (
    <Text fontSize="sm">
      {total}
      <small></small>
    </Text>
  );
};

// 続きはCodeSandbox上で。。。

CodeSandBox上にuseFieldArrayで請求書テーブルのコードを置いていますので、興味のある方はのぞいてみてください。

参考サイト:

23
9
1

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
23
9