3
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.

【React Final Form】 name="users[0].name" にすればオブジェクト・配列も管理できるよ【小ネタ】

Last updated at Posted at 2021-08-25

手前味噌ですが、React Final Form の使い方を1から知りたい場合は、 ↓の記事をどうぞ。

React Final Form の魅力は、 name Prop を使ってカンタンにフォームの状態を管理できるという点です。

その name に、ドットを含む文字列 (例 "users[2].name", dot-and-bracket syntax と呼ぶようです) を渡すことで、フィールドの値を、オブジェクトや配列の値として管理することが出来ます。

array.stories.tsx
export const Array = () => {
  const handleSubmit = () => {};
  return (
    <Form onSubmit={handleSubmit}>
      {({ handleSubmit }) => (
        <form onSubmit={handleSubmit}>
          {[0, 1, 2].map((i) => (
            <div key={i}>
              <Field name={`users[${i}].name`} component="input" placeholder="name"/>
              <Field name={`users[${i}].email`} component="input" placeholder="email"/>
            </div>
          ))}
          <h4>Value</h4>
          {/* ここから、フォームの値(values)を表示 */}
          <FormSpy>
            {({ values }) => (
              <pre>
                <code>{JSON.stringify(values, null, 2)}</code>
              </pre>
            )}
          </FormSpy>
        </form>
      )}
    </Form>
  );
};

スクリーンショット

image.png

参考記事

3
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
3
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?