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 specify record type in FunctionField #5370

Merged
merged 1 commit into from
Oct 8, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
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
9 changes: 5 additions & 4 deletions examples/demo/src/orders/NbItemsField.tsx
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
import * as React from 'react';
import { FC } from 'react';
import { FunctionField, Record } from 'react-admin';
import { FunctionField, FieldProps } from 'react-admin';
import { Order } from '../types';

const render = (record?: Record) => (record as Order).basket.length;
const render = (record?: Order) => record && record.basket.length;

const NbItemsField: FC = () => <FunctionField render={render} />;
const NbItemsField = ({ record }: FieldProps<Order>) => (
<FunctionField<Order> record={record} render={render} />
);

NbItemsField.defaultProps = {
label: 'Nb Items',
Expand Down
36 changes: 22 additions & 14 deletions packages/ra-ui-materialui/src/field/FunctionField.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import * as React from 'react';
import { FC, memo } from 'react';
import { useMemo } from 'react';
import { Record } from 'ra-core';
import Typography, { TypographyProps } from '@material-ui/core/Typography';

Expand All @@ -16,19 +16,27 @@ import { PublicFieldProps, InjectedFieldProps, fieldPropTypes } from './types';
* render={record => record && `${record.first_name} ${record.last_name}`}
* />
*/
const FunctionField: FC<FunctionFieldProps> = memo<FunctionFieldProps>(
({ className, record, source = '', render, ...rest }) =>
record ? (
<Typography
component="span"
variant="body2"
className={className}
{...sanitizeRestProps(rest)}
>
{render(record, source)}
</Typography>
) : null
);
const FunctionField = <RecordType extends Record = Record>({
className,
record,
source = '',
render,
...rest
}: FunctionFieldProps<RecordType>) =>
useMemo(
() =>
record ? (
<Typography
component="span"
variant="body2"
className={className}
{...sanitizeRestProps(rest)}
>
{render(record, source)}
</Typography>
) : null,
[className, record, source, render, rest]
);

FunctionField.defaultProps = {
addLabel: true,
Expand Down