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 ability to accept more than one child in <Reference> Fields #7812

Merged
merged 16 commits into from
Jun 16, 2022
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
219 changes: 177 additions & 42 deletions docs/ReferenceField.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,101 +5,236 @@ title: "The ReferenceField Component"

# `<ReferenceField>`

`<ReferenceField>` is useful for displaying many-to-one and one-to-one relationships. This component fetches a referenced record (using the `dataProvider.getMany()` method), and passes it to its child. A `<ReferenceField>` displays nothing on its own, it just fetches the data and expects its child to render it. Usual child components for `<ReferenceField>` are other `<Field>` components.
`<ReferenceField>` is useful for displaying many-to-one and one-to-one relationships, e.g. the details of a user when rendering a post authored by that user.

For instance, if a `post` has one author from the `users` resource, referenced by a `user_id` field, here is how to fetch the `user` related to each `post` record in a list, and display the `name` for each:
```
┌──────────────┐ ┌────────────────┐
│ posts │ │ users │
│--------------│ │----------------│
│ id │ ┌───│ id │
│ user_id │╾──┘ │ name │
│ title │ │ date_of_birth │
│ published_at │ └────────────────┘
└──────────────┘
```

```jsx
import * as React from "react";
import { List, Datagrid, ReferenceField, TextField, EditButton } from 'react-admin';
<ReferenceField source="user_id" reference="users">
<TextField source="name" />
</ReferenceField>
```

export const PostList = () => (
<List>
<Datagrid>
A `<ReferenceField>` displays nothing on its own, it just fetches the data, pust it in a [`RecordContext`](./useRecordContext.md), and lets its child to render it. Usual child components for `<ReferenceField>` are other `<Field>` components (e.g. [`<TextField>`](./TextField.md)).
fzaninotto marked this conversation as resolved.
Show resolved Hide resolved

This component fetches a referenced record (`users` in this example) using the `dataProvider.getMany()` method, and passes it to its child. It uses `dataProvider.getMany()` instead of `dataProvider.getOne()` for performance reasons. When using several `<ReferenceField>` in the same page (e.g. in a `<Datagrid>`), this allows to call the `dataProvider` once instead of once per row.

## Usage

For instance, let's consider a model where a `post` has one author from the `users` resource, referenced by a `user_id` field.

Here is how to render both a post and the `name` of its author in a show view:

```jsx
import { Show, SimpleShowLayout, ReferenceField, TextField, DateField } from 'react-admin';

export const PostShow = () => (
<Show>
<SimpleShowLayout>
<TextField source="id" />
<ReferenceField label="User" source="user_id" reference="users">
<TextField source="title" />
<DateField source="published_at" />
<ReferenceField label="Author" source="user_id" reference="users">
<TextField source="name" />
</ReferenceField>
<TextField source="title" />
<EditButton />
</Datagrid>
</List>
</SimpleShowLayout>
</Show>
);
```

With this configuration, `<ReferenceField>` wraps the user's name in a link to the related user `<Edit>` page.

![ReferenceField](./img/reference-field.png)

## Properties
## Props

| Prop | Required | Type | Default | Description |
| ----------- | -------- | ------------------- | -------- | ------------------------------------------------------------------------------------------------------------------- |
| `children` | Required | `ReactNode` | - | One or more Field elements used to render the referenced record |
| `reference` | Required | `string` | - | The name of the resource for the referenced records, e.g. 'posts' |
| `children` | Required | `Element` | - | The Field element used to render the referenced record |
| `label` | Optional | `string | Function` | `resources.[resource].fields.[source]` | Label to use for the field when rendered in layout components |
| `link` | Optional | `string | Function` | `edit` | Target of the link wrapping the rendered child. Set to `false` to disable the link. |
| `sortBy` | Optional | `string | Function` | `source` | Name of the field to use for sorting when the user clicks on the column header. |
| `sortBy` | Optional | `string | Function` | `source` | Name of the field to use for sorting when used in a Datagrid |

`<ReferenceField>` also accepts the [common field props](./Fields.md#common-field-props).

## `sx`: CSS API
## `label`

The `<ReferenceField>` component accepts the usual `className` prop. You can also override many styles of the inner components thanks to the `sx` property (as most MUI components, see their [documentation about it](https://mui.com/customization/how-to-customize/#overriding-nested-component-styles)). This property accepts the following subclasses:
By default, `<SimpleShowLayout>`, `<Datagrid>` and other layout components infer the label of a field based on its `source`. For a `<ReferenceField>`, this may not be what you expect:

| Rule name | Description |
|----------------------------|-------------------------------|
| `& .RaReferenceField-link` | Applied to each child element |
```jsx
{/* default label is 'User Id', or the translation of 'resources.posts.fields.user_id' if it exists */}
<ReferenceField source="user_id" reference="users" link="show">
<TextField source="name" />
</ReferenceField>
```

To override the style of all instances of `<ReferenceField>` using the [MUI style overrides](https://mui.com/customization/globals/#css), use the `RaReferenceField` key.
That's why you often need to set an explicit `label` on a `<RefezrenceField>`:
fzaninotto marked this conversation as resolved.
Show resolved Hide resolved

## Usage
```jsx
<ReferenceField label="Author name" source="user_id" reference="users" link="show">
<TextField source="name" />
</ReferenceField>
```

`<ReferenceField>` accepts a `reference` attribute, which specifies the resource to fetch for the related record.
## `link`

**Note**: You **must** add a `<Resource>` for the reference resource - react-admin needs it to fetch the reference data. You *can* omit the `list` prop in this reference if you want to hide it in the sidebar menu.
To change the link from the `<Edit>` page to the `<Show>` page, set the `link` prop to "show".

```jsx
<Admin dataProvider={myDataProvider}>
<Resource name="posts" list={PostList} />
<Resource name="users" />
</Admin>
<ReferenceField source="user_id" reference="users" link="show">
<TextField source="name" />
</ReferenceField>
```

To change the link from the `<Edit>` page to the `<Show>` page, set the `link` prop to "show".
You can also prevent `<ReferenceField>` from adding a link to children by setting `link` to `false`.

```jsx
<ReferenceField label="User" source="user_id" reference="users" link="show">
// No link
<ReferenceField source="user_id" reference="users" link={false}>
<TextField source="name" />
</ReferenceField>
```

By default, `<ReferenceField>` is sorted by its `source`. To specify another attribute to sort by, set the `sortBy` prop to the according attribute's name.
You can also use a custom `link` function to get a custom path for the children. This function must accept `record` and `reference` as arguments.

```jsx
<ReferenceField label="User" source="user_id" reference="users" sortBy="user.name">
// Custom path
<ReferenceField source="user_id" reference="users" link={(record, reference) => `/my/path/to/${reference}/${record.id}`}>
<TextField source="name" />
</ReferenceField>
```

You can also prevent `<ReferenceField>` from adding a link to children by setting `link` to `false`.
## `reference`

The resource to fetch for the related record.

For instance, if the `posts` resource has a `user_id` field, set the `reference` to `users` to fetch the user related to each post.

```jsx
// No link
<ReferenceField label="User" source="user_id" reference="users" link={false}>
<ReferenceField source="user_id" reference="users">
<TextField source="name" />
</ReferenceField>
```

You can also use a custom `link` function to get a custom path for the children. This function must accept `record` and `reference` as arguments.
## `sortBy`

By default, when used in a `<Datagrid>`, and when the user clicks on the column header of a `<ReferenceField>`, react-admins sorts the list by the field `source`. To specify another field name to sort by, set the `sortBy` prop.
fzaninotto marked this conversation as resolved.
Show resolved Hide resolved

```jsx
// Custom path
<ReferenceField label="User" source="user_id" reference="users" link={(record, reference) => `/my/path/to/${reference}/${record.id}`}>
<ReferenceField source="user_id" reference="users" sortBy="user.name">
<TextField source="name" />
</ReferenceField>
```

**Tip**: React-admin accumulates and deduplicates the ids of the referenced records to make *one* `dataProvider.getMany()` call for the entire list, instead of n `dataProvider.getOne()` calls. So for instance, if the API returns the following list of posts:
## `sx`: CSS API

The `<ReferenceField>` component accepts the usual `className` prop. You can also override many styles of the inner components thanks to the `sx` property (as most MUI components, see their [documentation about it](https://mui.com/customization/how-to-customize/#overriding-nested-component-styles)). This property accepts the following subclasses:

| Rule name | Description |
|----------------------------|-------------------------------|
| `& .RaReferenceField-link` | Applied to each child element |

To override the style of all instances of `<ReferenceField>` using the [MUI style overrides](https://mui.com/customization/globals/#css), use the `RaReferenceField` key.

## Rendering More Than One Field

You often need to render more than one field of the reference table (e.g. if the `users` table has a `first_name` and a `last_name` field).

Given that `<ReferenceField>` can accept more than one child, you can use as many `<Field>` as you like:

```jsx
import { Show, SimpleShowLayout, ReferenceField, TextField, DateField, FunctionField } from 'react-admin';

export const PostShow = () => (
<Show>
<SimpleShowLayout>
<TextField source="id" />
<TextField source="title" />
<DateField source="published_at" />
<ReferenceField label="Author" source="user_id" reference="users">
<TextField source="first_name" />{' '}
<TextField source="last_name" />
</ReferenceField>
</SimpleShowLayout>
</Show>
);
```

You can also use several `<ReferenceField>` for the same resource in a given view - react-admin will deduplicate them and only make one call to the distant table. This is useful e.g. is you want to have one label per field:

```jsx
import { Show, SimpleShowLayout, ReferenceField, TextField, DateField } from 'react-admin';

export const PostShow = () => (
<Show>
<SimpleShowLayout>
<TextField source="id" />
<TextField source="title" />
<DateField source="published_at" />
<ReferenceField label="First name" source="user_id" reference="users">
<TextField source="first_name" />
</ReferenceField>
<ReferenceField label="Last name" source="user_id" reference="users">
<TextField source="last_name" />
</ReferenceField>
</SimpleShowLayout>
</Show>
);
```

You can also use a [`<FunctionField>`](./FunctionField.md) to render a string composed of several fields.

```jsx
import { Show, SimpleShowLayout, ReferenceField, TextField, DateField, FunctionField } from 'react-admin';

export const PostShow = () => (
<Show>
<SimpleShowLayout>
<TextField source="id" />
<TextField source="title" />
<DateField source="published_at" />
<ReferenceField label="Name" source="user_id" reference="users">
<FunctionField render={record => `${record.first_name} ${record.last_name}`} />
</ReferenceField>
</SimpleShowLayout>
</Show>
);
```

## Performance

When used in a `<Datagrid>`, `<ReferenceField>` fetches the referenced record only once for the entire table.

![ReferenceField](./img/reference-field.png)

For instance, with this code:

```jsx
import { List, Datagrid, ReferenceField, TextField, EditButton } from 'react-admin';

export const PostList = () => (
<List>
<Datagrid>
<TextField source="id" />
<ReferenceField label="User" source="user_id" reference="users">
<TextField source="name" />
</ReferenceField>
<TextField source="title" />
<EditButton />
</Datagrid>
</List>
);
```

React-admin accumulates and deduplicates the ids of the referenced records to make *one* `dataProvider.getMany()` call for the entire list, instead of n `dataProvider.getOne()` calls. So for instance, if the API returns the following list of posts:

```js
[
Expand All @@ -121,4 +256,4 @@ You can also use a custom `link` function to get a custom path for the children.
]
```

Then react-admin renders the `<PostList>` with a loader for the `<ReferenceField>`, fetches the API for the related users in one call (`GET http://path.to.my.api/users?ids=[789,735]`), and re-renders the list once the data arrives. This accelerates the rendering and minimizes network load.
Then react-admin renders the `<PostList>` with a loader for the `<ReferenceField>`, fetches the API for the related users in one call (`dataProvider.getMany('users', { ids: [789,735] }`), and re-renders the list once the data arrives. This accelerates the rendering and minimizes network load.
29 changes: 15 additions & 14 deletions docs/ReferenceManyField.md
Original file line number Diff line number Diff line change
Expand Up @@ -33,20 +33,6 @@ export const PostList = () => (

![ReferenceManyFieldSingleFieldList](./img/reference-many-field-single-field-list.png)

## Properties

| Prop | Required | Type | Default | Description |
| ------------ | -------- | ------------------ | -------------------------------- | ----------------------------------------------------------------------------------- |
| `children` | Required | `Element` | - | The Iterator element used to render the referenced records |
| `reference` | Required | `string` | - | The name of the resource for the referenced records, e.g. 'books' |
| `target` | Required | string | - | Target field carrying the relationship on the referenced resource, e.g. 'user_id' |
| `filter` | Optional | `Object` | - | Filters to use when fetching the related records, passed to `getManyReference()` |
| `pagination` | Optional | `Element` | - | Pagination element to display pagination controls. empty by default (no pagination) |
| `perPage` | Optional | `number` | 25 | Maximum number of referenced records to fetch |
| `sort` | Optional | `{ field, order }` | `{ field: 'id', order: 'DESC' }` | Sort order to use when fetching the related records, passed to `getManyReference()` |

`<ReferenceManyField>` also accepts the [common field props](./Fields.md#common-field-props), except `emptyText` (use the child `empty` prop instead).

## Usage

`<ReferenceManyField>` accepts a `reference` attribute, which specifies the resource to fetch for the related record. It also accepts a `source` attribute which defines the field containing the value to look for in the `target` field of the referenced resource. By default, this is the `id` of the resource (`post.id` in the previous example).
Expand Down Expand Up @@ -121,3 +107,18 @@ Also, you can filter the query used to populate the possible values. Use the `fi
</ReferenceManyField>
```
{% endraw %}

## Props

| Prop | Required | Type | Default | Description |
| ------------ | -------- | ------------------ | -------------------------------- | ----------------------------------------------------------------------------------- |
| `children` | Required | `Element` | - | The Iterator element used to render the referenced records |
| `reference` | Required | `string` | - | The name of the resource for the referenced records, e.g. 'books' |
| `target` | Required | string | - | Target field carrying the relationship on the referenced resource, e.g. 'user_id' |
| `filter` | Optional | `Object` | - | Filters to use when fetching the related records, passed to `getManyReference()` |
| `pagination` | Optional | `Element` | - | Pagination element to display pagination controls. empty by default (no pagination) |
| `perPage` | Optional | `number` | 25 | Maximum number of referenced records to fetch |
| `sort` | Optional | `{ field, order }` | `{ field: 'id', order: 'DESC' }` | Sort order to use when fetching the related records, passed to `getManyReference()` |

`<ReferenceManyField>` also accepts the [common field props](./Fields.md#common-field-props), except `emptyText` (use the child `empty` prop instead).

8 changes: 8 additions & 0 deletions packages/ra-ui-materialui/src/field/ReferenceField.spec.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,9 @@ import { QueryClient } from 'react-query';
import { createTheme, ThemeProvider } from '@mui/material/styles';

import { ReferenceField } from './ReferenceField';
import { Children } from './ReferenceField.stories';
import { TextField } from './TextField';

const theme = createTheme({});

describe('<ReferenceField />', () => {
Expand Down Expand Up @@ -379,4 +381,10 @@ describe('<ReferenceField />', () => {
);
expect(screen.queryAllByRole('link')).toHaveLength(0);
});

it('should accept multiple children', async () => {
render(<Children />);
expect(screen.findByText('9780393966473')).not.toBeNull();
expect(screen.findByText('novel')).not.toBeNull();
});
});
14 changes: 13 additions & 1 deletion packages/ra-ui-materialui/src/field/ReferenceField.stories.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -87,8 +87,20 @@ export const Link = () => (
</Wrapper>
);

export const Children = () => (
<Wrapper>
<ReferenceField
source="detail_id"
reference="book_details"
link={false}
>
<TextField source="ISBN" /> <TextField source="genre" />
</ReferenceField>
</Wrapper>
);

export const Multiple = () => {
const [calls, setCalls] = useState([]);
const [calls, setCalls] = useState<any>([]);
const dataProviderWithLogging = {
getMany: (resource, params) => {
setCalls(calls =>
Expand Down
Loading