Skip to content

Improvement: Use Controller in react package to simplify and decouple form field implementation #184

@adityacodepublic

Description

@adityacodepublic

Problem

Many input fields across our UI packages are facing issues such as:

  • Default values not showing
  • Select components not registering values properly
  • undefined values being returned

These issues are consistently resolved when using useController from React Hook Form (RHF) instead of the register method.

While trying to resolve these issues, I ended up using useController in many fields.
https://github.com/adityacodepublic/autoform/tree/fix-bugs

Improvement Suggestion

Move to using Controller in the react package, in the AutoFormField component, instead of relying on register. This change would:

  1. Fix form behavior issues: Components behave as expected without bugs.
  2. Decouple UI lib. from RHF: The UI package becomes form-library-agnostic, avoiding peer dependency on RHF.
  3. Simplify usage: Users don’t need to use useController manually.
  4. Extensible: Allows us to support other form libraries like TanStack Forms in the future with minimal changes.

Additional Context

  • We are already using useController instead of register in many ui libs.
  • Since Controller wraps only the FieldComponent inside AutoFormField, re-renders are scoped to just the FieldComponent. The outer AutoFormField or FieldWrapper does not re-render on controlled state changes.
  return (
    <FieldWrapper
      label={getLabel(field)}
      error={error}
      id={fullPath}
      field={field}
    >
      <Controller
        name={fullPath}
        disabled={field.fieldConfig?.inputProps?.disabled}
        render={({ field: formField }) => (
          <FieldComponent
            label={getLabel(field)}
            field={field}
            value={value}
            error={error}
            id={fullPath}
            key={fullPath}
            path={path}
            inputProps={{
              error: error,
              key: `${fullPath}-input`,
              ...field.fieldConfig?.inputProps,
              ...formField,
            }}
          />
        )}
      />
    </FieldWrapper>
  );
};

@vantezzen Let me know your thoughts — happy to help implement this if it looks good to you.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions