Skip to content

Releases: react-hook-form/lenses

v0.2.0

05 Mar 06:56
7716194
Compare
Choose a tag to compare

0.2.0 (2025-03-05)

Features

  • Add Quickstart story and refactor example component (#4) (99ef1ec)
  • update behaviour of union type. (#3) (d5a0290)

Version 0.1.1

26 Feb 10:32
Compare
Choose a tag to compare

🎊 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