--- layout: default title: "The ReferenceField Component" storybook_path: ra-ui-materialui-fields-referencefield--basic --- # `` `` 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. ## Usage For instance, let's consider a model where a `post` has one author from the `users` resource, referenced by a `user_id` field. ``` ┌──────────────┐ ┌────────────────┐ │ posts │ │ users │ │--------------│ │----------------│ │ id │ ┌───│ id │ │ user_id │╾──┘ │ name │ │ title │ │ date_of_birth │ │ published_at │ └────────────────┘ └──────────────┘ ``` In that case, use `` to display the post author's as follows: ```jsx import { Show, SimpleShowLayout, ReferenceField, TextField, DateField } from 'react-admin'; export const PostShow = () => ( ); ``` `` fetches the data, puts it in a [`RecordContext`](./useRecordContext.md), and renders the [`recordRepresentation`](./Resource.md#recordrepresentation) (the record `id` field by default) wrapped in a link to the related user `` page. ![ReferenceField](./img/reference_field_show.png) So it's a good idea to configure the `` to render related records in a meaningful way. For instance, for the `users` resource, if you want the `` to display the full name of the author: ```jsx `${record.first_name} ${record.last_name}`} /> ``` Alternately, if you pass a child component, `` will render it instead of the `recordRepresentation`. Usual child components for `` are other `` components (e.g. [``](./TextField.md)). ```jsx ``` 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](#performance). When using several `` in the same page (e.g. in a ``), this allows to call the `dataProvider` once instead of once per row. ## Props | Prop | Required | Type | Default | Description | | -------------- | --------------- | --------------------------------------------------------------------------------- | --------- | ---------------------------------------------------------------------------------------------------- | | `source` | Required | `string` | - | Name of the property to display | | `reference` | Required | `string` | - | The name of the resource for the referenced records, e.g. 'posts' | | `children` | Optional * | `ReactNode` | - | One or more Field elements used to render the referenced record | | `render` | Optional * | (referenceFieldContext) => `ReactNode` | - | A function used to render the referenced record, receive the reference field context as its argument | | `empty` | Optional | `ReactNode` | - | What to render when the field has no value or when the reference is missing | | `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. | | `offline` | Optional | `ReactNode` | - | What to render when there is no network connectivity when loading the record | | `queryOptions` | Optional | [`UseQuery Options`](https://tanstack.com/query/v5/docs/framework/react/reference/useQuery) | `{}` | `react-query` client options | | `sortBy` | Optional | `string | Function` | `source` | Name of the field to use for sorting when used in a Datagrid | `*` You must provide either `children` or `render`. `` also accepts the [common field props](./Fields.md#common-field-props). ## `children` By default, `` renders the `recordRepresentation` of the referenced record (the `id` field by default). You can customize this by passing one or more child components. Since `` creates a `RecordContext` for the referenced record, you can use any field component as a child, such as ``, ``, ``, etc. ```tsx ``` Alternatively, you can use [the `render` prop](#render) to render the referenced record in a custom way. ## `empty` `` can display a custom message when the referenced record is missing, thanks to the `empty` prop. ```jsx ``` `` renders the `empty` element when: - the referenced record is missing (no record in the `users` table with the right `user_id`), or - the field is empty (no `user_id` in the record). When `empty` is a string, `` renders it as a `` and passes the text through the i18n system, so you can use translation keys to have one message for each language supported by the interface: ```jsx ``` You can also pass a React element to the `empty` prop: ```jsx Missing user} /> ``` ## `label` By default, ``, `` and other layout components infer the label of a field based on its `source`. For a ``, this may not be what you expect: ```jsx {/* default label is 'User Id', or the translation of 'resources.posts.fields.user_id' if it exists */} ``` That's why you often need to set an explicit `label` on a ``: ```jsx ``` **Tip**: Having to specify the `label` prop on the field for it to be used by the Datagrid is no longer necessary with [``](./DataTable.md), the successor of the `` component. Instead, `` properly separates the props for the column header and the field itself, thanks to the [``](./DataTable.md#datatablecol) component. React-admin uses [the i18n system](./Translation.md) to translate the label, so you can use translation keys to have one label for each language supported by the interface: ```jsx ``` ## `link` To change the link from the `` page to the `` page, set the `link` prop to "show". ```jsx ``` You can also prevent `` from adding a link to children by setting `link` to `false`. ```jsx // No link ``` 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 // Custom path `/my/path/to/${reference}/${record.id}`} /> ``` ## `offline` When the user is offline, `` is smart enough to display the referenced record if it was previously fetched. However, if the referenced record has never been fetched before, `` displays an error message explaining that the app has lost network connectivity. You can customize this error message by passing a React element or a string to the `offline` prop: ```jsx No network, could not fetch data} > ... ... ``` ## `queryOptions` Use the `queryOptions` prop to pass options to [the `dataProvider.getMany()` query](./useGetOne.md#aggregating-getone-calls) that fetches the referenced record. For instance, to pass [a custom `meta`](./Actions.md#meta-parameter): {% raw %} ```jsx ``` {% endraw %} ## `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 ``` ## `render` Alternatively to `children`, you can pass a `render` prop to ``. It will receive the `ReferenceFieldContext` as its argument, and should return a React node. This allows to inline the render logic for the list of related records. ```jsx { if (isPending) { return

Loading...

; } if (error) { return

{error.message}

; } return

{referenceRecord.name}

; }} /> ``` ## `sortBy` By default, when used in a ``, and when the user clicks on the column header of a ``, react-admin sorts the list by the field `source`. To specify another field name to sort by, set the `sortBy` prop. ```jsx ``` **Tip**: Having to specify the `sortBy` prop on the field for it to be used by the Datagrid is no longer necessary with [``](./DataTable.md), the successor of the `` component. Instead, `` properly separates the props for the column header and the field itself, thanks to the [``](./DataTable.md#datatablecol) component. ## `sx`: CSS API The `` component accepts the usual `className` prop. You can also override many styles of the inner components thanks to the `sx` property (see [the `sx` documentation](./SX.md) for syntax and examples). This property accepts the following subclasses: | Rule name | Description | | -------------------------- | ----------------------------- | | `& .RaReferenceField-link` | Applied to each child element | To override the style of all instances of `` using the [application-wide style overrides](./AppTheme.md#theming-individual-components), use the `RaReferenceField` key. ## Performance When used in a ``, `` fetches the referenced record only once for the entire table. ![ReferenceField](./img/reference-field.png) For instance, with this code: ```jsx import { List, DataTable, ReferenceField, EditButton } from 'react-admin'; export const PostList = () => ( ); ``` 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 [ { id: 123, title: 'Totally agree', user_id: 789, }, { id: 124, title: 'You are right my friend', user_id: 789 }, { id: 125, title: 'Not sure about this one', user_id: 735 } ] ``` Then react-admin renders the `` with a loader for the ``, 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. ## Prefetching When you know that a page will contain a ``, you can configure the main page query to prefetch the referenced records to avoid a flicker when the data arrives. To do so, pass a `meta.prefetch` parameter to the page query. For example, the following code prefetches the authors referenced by the posts: {% raw %} ```jsx const PostList = () => ( {/** renders without an additional request */} ); ``` {% endraw %} **Note**: For prefetching to function correctly, your data provider must support [Prefetching Relationships](./DataProviders.md#prefetching-relationships). Refer to your data provider's documentation to verify if this feature is supported. **Note**: Prefetching is a frontend performance feature, designed to avoid flickers and repaints. It doesn't always prevent `` to fetch the data. For instance, when coming to a show view from a list view, the main record is already in the cache, so the page renders immediately, and both the page controller and the `` controller fetch the data in parallel. The prefetched data from the page controller arrives after the first render of the ``, so the data provider fetches the related data anyway. But from a user perspective, the page displays immediately, including the ``. If you want to avoid the `` to fetch the data, you can use the React Query Client's `staleTime` option. ## 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 `` can accept more than one child, you can use as many `` as you like: ```jsx import { Show, SimpleShowLayout, ReferenceField, TextField, DateField, FunctionField } from 'react-admin'; export const PostShow = () => ( {' '} ); ``` You can also use several `` 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 = () => ( ); ``` You can also use a [``](./FunctionField.md) to render a string composed of several fields. ```jsx import { Show, SimpleShowLayout, ReferenceField, TextField, DateField, FunctionField } from 'react-admin'; export const PostShow = () => ( `${record.first_name} ${record.last_name}`} /> ); ``` ## Removing The Link You can prevent `` from adding a link to its children by setting `link` to `false`. ```jsx // No link ``` ## Access Control If your authProvider implements [the `canAccess` method](./AuthProviderWriting.md#canaccess) and you don't provide the [`link`](#link) prop, React-Admin will verify whether users have access to the Show and Edit views. For instance, given the following `ReferenceField`: ```jsx ``` React-Admin will call `canAccess` with the following parameters: - If the `users` resource has a Show view: `{ action: "show", resource: 'posts', record: Object }` - If the `users` resource has an Edit view: `{ action: "edit", resource: 'posts', record: Object }`