Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add a default unique id for useInput #9788

Merged
merged 16 commits into from May 2, 2024
Merged
32 changes: 32 additions & 0 deletions cypress/e2e/create.cy.js
Expand Up @@ -15,6 +15,38 @@ describe('Create Page', () => {
CreatePage.waitUntilVisible();
});

it('should validate unique fields', () => {
CreatePage.logout();
LoginPage.login('admin', 'password');

UserCreatePage.navigate();
UserCreatePage.setValues([
{
type: 'input',
name: 'name',
value: 'Annamarie Mayer',
},
]);
cy.get(UserCreatePage.elements.input('name')).blur();

cy.get(CreatePage.elements.nameError)
.should('exist')
.contains('Must be unique', { timeout: 10000 });

UserCreatePage.setValues([
{
type: 'input',
name: 'name',
value: 'Annamarie NotMayer',
},
]);
cy.get(UserCreatePage.elements.input('name')).blur();

cy.get(CreatePage.elements.nameError)
.should('exist')
.should('not.contain', 'Must be unique', { timeout: 10000 });
});

it('should show the correct title in the appBar', () => {
cy.get(CreatePage.elements.title).contains('Create Post');
});
Expand Down
2 changes: 1 addition & 1 deletion cypress/support/CreatePage.js
Expand Up @@ -23,7 +23,7 @@ export default url => ({
title: '#react-admin-title',
userMenu: 'button[aria-label="Profile"]',
logout: '.logout',
nameError: '#name-helper-text',
nameError: '.MuiFormHelperText-root',
},

navigate() {
Expand Down
20 changes: 10 additions & 10 deletions docs/useInput.md
Expand Up @@ -41,16 +41,16 @@ const TitleInput = ({ source, label }) => {

## Props

| Prop | Required | Type | Default | Description |
|----------------|----------|--------------------------------|---------|-------------------------------------------------------------------|
| `source` | Required | `string` | - | The name of the field in the record |
| `defaultValue` | Optional | `any` | - | The default value of the input |
| `format` | Optional | `Function` | - | A function to format the value from the record to the input value |
| `parse` | Optional | `Function` | - | A function to parse the value from the input to the record value |
| `validate` | Optional | `Function` | `Function[]` | - | A function or an array of functions to validate the input value |
| `id` | Optional | `string` | - | The id of the input |
| `onChange` | Optional | `Function` | - | A function to call when the input value changes |
| `onBlur` | Optional | `Function` | - | A function to call when the input is blurred |
| Prop | Required | Type | Default | Description |
|----------------|----------|--------------------------------|--------------------------- |-------------------------------------------------------------------|
| `source` | Required | `string` | - | The name of the field in the record |
| `defaultValue` | Optional | `any` | - | The default value of the input |
| `format` | Optional | `Function` | - | A function to format the value from the record to the input value |
| `parse` | Optional | `Function` | - | A function to parse the value from the input to the record value |
| `validate` | Optional | `Function` | `Function[]` | - | A function or an array of functions to validate the input value |
| `id` | Optional | `string` | `r[input number]-[source]` | The id of the input |
| `onChange` | Optional | `Function` | - | A function to call when the input value changes |
| `onBlur` | Optional | `Function` | - | A function to call when the input is blurred |

Additional props are passed to [react-hook-form's `useController` hook](https://react-hook-form.com/docs/usecontroller).

Expand Down
2 changes: 1 addition & 1 deletion packages/ra-core/src/form/useInput.spec.tsx
Expand Up @@ -58,7 +58,7 @@ describe('useInput', () => {
</CoreAdminContext>
);

expect(inputProps.id).toEqual('title');
expect(inputProps.id).toEqual('r0-title');
expect(inputProps.isRequired).toEqual(true);
expect(inputProps.field).toBeDefined();
expect(inputProps.field.name).toEqual('title');
Expand Down
43 changes: 43 additions & 0 deletions packages/ra-core/src/form/useInput.stories.tsx
@@ -0,0 +1,43 @@
import * as React from 'react';
import { CoreAdminContext } from '../core';
import { Form } from './Form';
import { useInput } from './useInput';

export default {
title: 'ra-core/form/useInput',
};

const Input = ({ source }) => {
const { id, field, fieldState } = useInput({ source });

return (
<label htmlFor={id}>
{id}: <input id={id} {...field} />
{fieldState.error && <span>{fieldState.error.message}</span>}
</label>
);
};

export const Basic = () => {
const [submittedData, setSubmittedData] = React.useState<any>();
return (
<CoreAdminContext>
<Form onSubmit={data => setSubmittedData(data)}>
<div
style={{
display: 'flex',
flexDirection: 'column',
gap: '1em',
marginBottom: '1em',
}}
>
<Input source="field1" />
<Input source="field2" />
<Input source="field3" />
</div>
<button type="submit">Submit</button>
</Form>
<pre>{JSON.stringify(submittedData, null, 2)}</pre>
</CoreAdminContext>
);
};
7 changes: 5 additions & 2 deletions packages/ra-core/src/form/useInput.ts
@@ -1,4 +1,4 @@
import { ReactElement, useEffect } from 'react';
import { ReactElement, useEffect, useId } from 'react';
import {
ControllerFieldState,
ControllerRenderProps,
Expand Down Expand Up @@ -44,6 +44,7 @@ export const useInput = <ValueType = any>(
const formGroupName = useFormGroupContext();
const formGroups = useFormGroups();
const record = useRecordContext();
const defaultId = useId();

if (
!source &&
Expand Down Expand Up @@ -132,7 +133,9 @@ export const useInput = <ValueType = any>(
};

return {
id: id || finalSource,
id:
id ||
`${defaultId.substring(1, defaultId.length - 1)}-${finalSource}`,
field,
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why not just defaultId?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It was to be more readable.
Applied

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't understand why you substring

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

removed

fieldState,
formState,
Expand Down
4 changes: 2 additions & 2 deletions packages/ra-input-rich-text/src/RichTextInput.spec.tsx
Expand Up @@ -9,7 +9,7 @@ describe('<RichTextInput />', () => {
const { container, rerender } = render(<Basic record={record} />);

await waitFor(() => {
expect(container.querySelector('#body')?.innerHTML).toEqual(
expect(container.querySelector('#r0-body')?.innerHTML).toEqual(
'<h1>Hello world!</h1>'
);
});
Expand All @@ -18,7 +18,7 @@ describe('<RichTextInput />', () => {
rerender(<Basic record={newRecord} />);

await waitFor(() => {
expect(container.querySelector('#body')?.innerHTML).toEqual(
expect(container.querySelector('#r0-body')?.innerHTML).toEqual(
'<h1>Goodbye world!</h1>'
);
});
Expand Down
Expand Up @@ -86,9 +86,9 @@ describe('<RadioButtonGroupInput />', () => {
);
expect(screen.queryByText('People')).not.toBeNull();
const input1 = screen.getByLabelText('Leo Tolstoi');
expect(input1.id).toBe('type_123');
expect(input1.id).toMatch(/r\d-type_123/);
const input2 = screen.getByLabelText('Jane Austen');
expect(input2.id).toBe('type_456');
expect(input2.id).toMatch(/r\d-type_456/);
});

it('should trigger custom onChange when clicking radio button', async () => {
Expand Down