React Hook Form and breaking up form components

I'm trying to convert a previous app to t3 stack and use some of the libs that I've seen theo use to simplify the code and make it work more consistently. So far most things are going great, but the point I'm stuck on is converting some of my more complex forms to react-hook-form.

For some background my most complex form currently consists of a few reusable "dumb" form segments. These segments take an object as a value and call an onChange() function with an updated version of the whole object whenever one of the fields is modified. The top-level component has a state variable that contains all of these sub-objects. When the user is done with the form the entire object is checked and submitted to the api endpoint. These are the issues I'm having:

1) My first thought was to treat each one of my dumb form segments as a controlled input wrapped with a
<Controller />
. However, if I want to be able to display errors on the text fields in the sub-component I don't think I can do that. Is this correct?

2) Assuming I can't do (1), then I need to pass the form methods down into each form segment to allow me to access the
errors
objects. Here, typing becomes an issue. The form segment is designed to be re-used in several different contexts, not always as part of the same form. So when I pass the form methods down to the segment I don't know what generic type to give them. I know the type that this segment of the form is supposed to deal with, but the controller passed down to me is for the top-level form, not this subsection. Below is a simplified example:

function FormSegment1(props: FormSegment1Props) {
  // The formMethods returned here has the type of `MyForm.settings`
  // How can I say here that I don't know the type of the whole object
  // but that some part of it will be a `{ firstName: string, lastName: string }`
  // so that I can reference those fields / types here?
  const formMethods = useFormContext();

  ...
}

function MyForm1() {
  const [settings, setSettings] = useState({
    //a bunch of other things
    formSegment1: {
      firstName: "",
      lastName: "",
    }
  })

  return (
    <FormProvider {...methods}>
      <form>
        <FormSegment1 />
      </form>
    </FormProvider>
  )
}


3) In general, this all feels very complicated. I really want to have reusable form segments because some parts of my forms get quite complex and I need to decompose them. Is react-hook-form the best tool for this job?
Was this page helpful?