Skip to content

Conversation

LeCarbonator
Copy link
Contributor

@LeCarbonator LeCarbonator commented Jul 8, 2025

Related issue: #1506

This PR implements a way to create 'branded' field components. Those special field components may only be used if the AppField's value matches it.

TODOS

  • Can it be generic somehow? Can the component access that?
  • Check need for implementation (and implement)
    • React
    • Solid
    • Angular
  • Amend documentation of Form Composition
    • React
    • Solid
    • Angular
  • Unit tests

The issue

interface TextFieldProps {
  label: string
}

function TextField(props: TextFieldProps) {
  // we assume our field will be of type string
  const field = useFieldContext<string>();

  return <></>;
}

const { useAppForm } = createFormHook({
  fieldContext,
  formContext,
  fieldComponents: {
    TextField
  },
  formComponents: {},
})

function App() {
  const form = useAppForm({
    defaultValues: {
      a: '',
      b: 0,
    },
  })
 

  return (
    <>
      <form.AppField name="a">
        {(field) => {
          // okay, because 'a' is a string
          return <field.TextField label="" />;
        }}
      </form.AppField>
      <form.AppField name="b">
        {(field) => {
          // oops! 'b' is a number, not a string. No error shows up
          return <field.TextField label="" />;
        }}
      </form.AppField>
    </>
  )
}

The solution

The PR addresses it as follows (feedback is appreciated!):

interface TextFieldProps {
  label: string
}

function TextField(props: TextFieldProps) {
  // we assume our field will be of type string
  const field = useFieldContext<string>();

  return <></>;
}

// we're creating a field component restricted to strings, with the properties of TextFieldProps
const TextFieldComponent = createFieldComponent<string, TextFieldProps>(TextField);

const { useAppForm } = createFormHook({
  fieldContext,
  formContext,
  fieldComponents: {
    TextField: TextFieldComponent,
    OldTextField: TextField
  },
  formComponents: {},
})

function App() {
  const form = useAppForm({
    defaultValues: {
      a: '',
      b: 0,
    },
  })
 

  return (
    <>
      <form.AppField name="a">
        {(field) => (
          <>
             {/* Okay, because 'a' is a string */}
             <field.TextField label="" />
             <field.OldTextField label="" />
          </>
        )}
      </form.AppField>
      <form.AppField name="b">
        {(field) => (
          <>
            {/* Error! TextField cannot be used on number fields */}
            <field.TextField label="" />
             {/* Directly passed compoents are considered 'global' */}
             <field.OldTextField />
          </>
        }}
      </form.AppField>
    </>
  )
}

Copy link

nx-cloud bot commented Jul 8, 2025

🤖 Nx Cloud AI Fix Eligible

An automatically generated fix could have helped fix failing tasks for this run, but Self-healing CI is disabled for this workspace. Visit workspace settings to enable it and get automatic fixes in future runs.

To disable these notifications, a workspace admin can disable them in workspace settings.


View your CI Pipeline Execution ↗ for commit a8231cc

Command Status Duration Result
nx affected --targets=test:sherif,test:knip,tes... ❌ Failed 29s View ↗
nx run-many --target=build --exclude=examples/** ❌ Failed 4s View ↗

☁️ Nx Cloud last updated this comment at 2025-10-05 12:25:05 UTC

Copy link

pkg-pr-new bot commented Jul 8, 2025

Copy link

codecov bot commented Jul 9, 2025

Codecov Report

Attention: Patch coverage is 33.33333% with 2 lines in your changes missing coverage. Please review.

Project coverage is 43.03%. Comparing base (6510d8b) to head (24f9ef3).
Report is 2 commits behind head on main.

Files with missing lines Patch % Lines
packages/react-form/src/createFormHook.tsx 33.33% 2 Missing ⚠️
Additional details and impacted files
@@             Coverage Diff             @@
##             main    #1606       +/-   ##
===========================================
- Coverage   89.55%   43.03%   -46.52%     
===========================================
  Files          34       13       -21     
  Lines        1493      158     -1335     
  Branches      370       26      -344     
===========================================
- Hits         1337       68     -1269     
+ Misses        139       79       -60     
+ Partials       17       11        -6     

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@LeCarbonator LeCarbonator marked this pull request as ready for review September 15, 2025 21:02
@LeCarbonator
Copy link
Contributor Author

Wow. You'd think if one misclick is able to mark a PR as ready for review, you'd have the option to mark it as draft on mobile.

Doesn't seem to be possible. I'll mark it as draft again when I'm on desktop ...

@LeCarbonator LeCarbonator marked this pull request as draft September 16, 2025 14:43
@adamkangas
Copy link

The current implementation works great for simple types, and I could certainly make use of it for my most common form fields to cut down on some boilerplate and current need to pass field or value into the component for "full" type safety.

What were you wondering about specifically in terms of generics?

I've had a play with trying to register a generic form components similar to <RecordSelect /> which has a value of TValue | null (where TValue extends { id: string; })

After registering the component, it's fairly straightforward to define various simple data shapes that extend {id: string;} and store them in form fields. These easily qualify for the generic field.RecordSelect because they satisfy AppFieldComponentsOfType.

However, the component ends up locked to a strict option type of { id: string; }

I'm no library-level TS wizard so I'm a bit grasping at straws for we'd ever be able to inject the correct type values into these generic components at the AppField level, where we know the concrete TData we're dealing with. Perhaps there's an approach where we're registering functions conforming to a certain signature which in turn return components, instead of registering the components themselves? (This is more "can we do it?" than "should we do it?" thinking)

@LeCarbonator
Copy link
Contributor Author

You mean a case where the component has properties that should adapt to the field value using it?

Yeah, that is very difficult in the current iteration of this PR, which is why it has been stale while I consider some other options.

A simple example of this would also be Radio buttons. The value of the radio button should not be string, but restricted to the field value using it (Example: 'a' | 'b'). A generic component solves this very easily, but this implementation cannot be compatible with it.

@adamkangas
Copy link

adamkangas commented Oct 1, 2025

Yes, Radio and a basic Select (constrained to a string union) are simpler examples of the challenges here.

This crude API seems to work in my application code, the challenge would obviously be to feed createGenericFoo functions into createFormHook() and get properly-scoped GenericFoo components outputted on AppField

function makeCreateGenericFieldComponent<
  TBaseFieldValue, // For use in AppFieldComponentsOfType or an equivalent helper
  TGetScopedComponent extends <T extends TBaseFieldValue>(value: T) => React.FC<any>, // Allows us to get the scoped component once we know the field value
>(args: { baseFieldValue: TBaseFieldValue; getScopedComponent: TGetScopedComponent }) {
  return args
}

// We would want to somehow pass this into createFormHook
const createGenericSelect = makeCreateGenericFieldComponent({
  baseFieldValue: '' as string, 
  getScopedComponent: <TValue extends string>(value: TValue) => {
    return Select<TValue>
  },
})

// We would want something like this to happen inside AppField once we have access to the field value
const myAnimal = "dog" as "dog" | "cat" | "bird";
const AnimalSelect = createGenericSelect.getScopedComponent(myAnimal);
//     ^ yay correctly inferred as Select<"dog" | "cat" | "bird">

For this UI element:

type SelectFieldProps<TValue extends string> = {
  label: string
  options: readonly TValue[]
  getOptionLabel?: (option: TValue) => string
}

function Select<TValue extends string>({
  label,
  options,
  getOptionLabel,
}: SelectFieldProps<TValue>) {
  const field = useFieldContext<TValue>()
  return (
    <label>
      <div>{label}</div>
      <select
        value={field.state.value}
        onChange={(e) => {
          const option = options.find((o) => o === e.target.value)
          if (!option) throw new Error('Invariant')
          field.handleChange(option)
        }}
      >
        {options.map((option, index) => (
          <option key={index} value={option}>
            {getOptionLabel ? getOptionLabel(option) : option}
          </option>
        ))}
      </select>
    </label>
  )
}

@LeCarbonator
Copy link
Contributor Author

Sounds interesting! After some other PR work, I'll freshen this one up a bit and see if I can find a nice solution for it.

Copy link

changeset-bot bot commented Oct 5, 2025

⚠️ No Changeset found

Latest commit: a8231cc

Merging this PR will not cause a version bump for any packages. If these changes should not result in a new version, you're good to go. If these changes should result in a version bump, you need to add a changeset.

This PR includes no changesets

When changesets are added to this PR, you'll see the packages that this PR includes changesets for and the associated semver types

Click here to learn what changesets are, and how to add one.

Click here if you're a maintainer who wants to add a changeset to this PR

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants