Releases: react-hook-form/lenses
Releases · react-hook-form/lenses
v0.2.0
Version 0.1.1
🎊 Features
- Type-Safe Form State: Focus on specific parts of your form state with full TypeScript support and precise type inference
- Functional Lenses: Build complex form state transformations through composable lens operations
- Deep Structure Support: Handle deeply nested structures and arrays elegantly with specialized array operations
- Seamless Integration: Work smoothly with React Hook Form's Control API and existing functionality
- Optimized Performance: Each lens is cached and reused for optimal performance
- Array Handling: Specialized support for array fields with type-safe mapping
- Composable API: Build complex form state transformations through lens composition
⏰ Quickstart
import { useFieldArray, useForm } from 'react-hook-form';
import { Lens, useLens } from '@hookform/lenses';
function FormComponent() {
const { handleSubmit, control } = useForm<{
firstName: string;
lastName: string;
children: {
name: string;
surname: string;
}[];
}>({});
const lens = useLens({ control });
const children = lens.focus('children');
const { fields: childrenFields } = useFieldArray(children.interop());
return (
<form onSubmit={handleSubmit(console.log)}>
<PersonForm
lens={lens.reflect((l) => ({
name: l.focus('firstName'),
surname: l.focus('lastName'),
}))}
/>
{children.map(childrenFields, (l, key) => (
<PersonForm key={key} lens={l} />
))}
<input type="submit" />
</form>
);
}
function PersonForm({ lens }: { lens: Lens<{ name: string; surname: string }> }) {
return (
<>
<StringInput lens={lens.focus('name')} />
<StringInput lens={lens.focus('surname')} />
</>
);
}
function StringInput({ lens }: { lens: Lens<string> }) {
return <input {...lens.interop((ctrl, name) => ctrl.register(name))} />;
}
All credits go to @aspirisen