Ad

Show Tab Form Validation For Inputs Not Direct Children Of

- 1 answer

When an unfocused tab has a validation error, the tab header should appear red. Instead of that, when an unfocused tab has a validation error, the tab header does not give any indication of the error.

This issue happens when I'm using subcomponents. If all the components are defined at the Create/Edit level, then the tab turns red as expected. But if there are nested components, then the tab does not.

Is there a way I can "pass" the validation to my custom component or mark my custom fields as invalid so the tabs are properly marked in red when they have an invalid field?

In my code, for example, I use a custom input as subcomponent. While the inputs turn on red when invalid, the tabs does not.

  • This code works.
export const ProductCreate = (props) => (
  <Create {...props}>
    <TabbedForm>
      <FormTab label="settings">
        <Field component={TextInput} name="name" label="Name" validate={required} {...props} />
        <SettingsTab />
      </FormTab>
      <FormTab label="sizes">
        <SizesTab />
      </FormTab>
    </TabbedForm>
   </Create>
);
  • By moving the field into a subcomponent, the validation indicator does not work.
export const ProductCreate = (props) => (
  <Create {...props}>
    <TabbedForm>
      <FormTab label="settings">
        <SettingsTab />
      </FormTab>
      <FormTab label="sizes">
        <SizesTab />
      </FormTab>
    </TabbedForm>
  </Create>
);


export const SettingsTab = (props) => (
  <div>
    <Field component={TextInput} name="name" label="Name" validate={required} {...props} />
  </div>
);

I'm stuck with this issue and I can't change my current react-admin version ([email protected]^2.9.3) without breaking many dependencies on my project.

Ad

Answer

Recently I got stuck with the same problem as OP.

Checked the source code and found out that in react-admin the FormTab component expects to directly contain input fields. And TabbedForm marks its tabs as invalid whenever some tab has a field in which validation has failed. This stops working when the input field wrapped in another component.

Check this link to the source code for more information: https://github.com/marmelab/react-admin/blob/872480a9a4a8491066eb8b1f0f651e48f47e9080/packages/ra-ui-materialui/src/form/TabbedForm.tsx#L347

To overcome this issue I came up with this "hacky" solution:

// A component that does nothing and accepts any properties
const Dummy = (props: any) => (<></>);

...

<FormTab label="My tab" path="my-tab">
    <MyCustomComponentThatContainsInputFields {...props} />

    {/* As many Dummy components as MyCustomComponentThatContainsInputFields contains inputs.
They just indicate that this FormTab contains particular input fields */}
    <Dummy source="input_1" />
    <Dummy source="input_2" />
    ...
</FormTab>

...
Ad
source: stackoverflow.com
Ad