コンポーネントがシングルトンであると想定できないためhtmlFor
、ラベルとフィールドへの付与を自動的に処理しようとしています。以下では、最初のレンダリング時にフォームの一意の ID をメモするためにuseMemo
、lodash を使用しています。uniqueId
IDをuseMemo
再計算しないように、2 番目の引数として空の配列を指定する必要がありました。でこれを処理する自動化された方法はありfinal-form
ますか?
import React, { useMemo } from 'react';
import { Form, Field } from 'react-final-form';
import { uniqueId } from 'lodash';
function TaskForm() {
const id = useMemo(() => uniqueId('_form'), []);
const getFor = name => name + id;
return (
<>
<h3>Create a task</h3>
<Form onSubmit={onSubmit}>
{({ handleSubmit, pristine, invalid, ...rest }) => {(
<form onSubmit={handleSubmit}>
<div className="form-group">
<label htmlFor={getFor('firstName')}>First Name</label>
<Field name="firstName" id={getFor('firstName')} component="input" placeholder="First Name" />
</div>
<button type="submit" disabled={pristine || invalid}>Submit</button>
</form>
)}}
</Form>
</>
);
}