-
-
Notifications
You must be signed in to change notification settings - Fork 5.3k
/
Copy pathFunctionField.tsx
54 lines (49 loc) · 1.57 KB
/
FunctionField.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
import * as React from 'react';
import { useMemo } from 'react';
import { useRecordContext } from 'ra-core';
import PropTypes from 'prop-types';
import Typography, { TypographyProps } from '@mui/material/Typography';
import { sanitizeFieldRestProps } from './sanitizeFieldRestProps';
import { FieldProps, fieldPropTypes } from './types';
/**
* Field using a render function
*
* @example
* <FunctionField
* source="last_name" // used for sorting
* label="Name"
* render={record => record && `${record.first_name} ${record.last_name}`}
* />
*/
export const FunctionField = <RecordType extends Record<string, unknown> = any>(
props: FunctionFieldProps<RecordType>
) => {
const { className, source = '', render, ...rest } = props;
const record = useRecordContext(props);
return useMemo(
() =>
record ? (
<Typography
component="span"
variant="body2"
className={className}
{...sanitizeFieldRestProps(rest)}
>
{render(record, source)}
</Typography>
) : null,
[className, record, source, render, rest]
);
};
FunctionField.propTypes = {
// @ts-ignore
...Typography.propTypes,
...fieldPropTypes,
render: PropTypes.func.isRequired,
};
export interface FunctionFieldProps<
RecordType extends Record<string, unknown> = any
> extends FieldProps<RecordType>,
Omit<TypographyProps, 'textAlign'> {
render: (record?: RecordType, source?: string) => any;
}