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 <Datagrid rowSx> prop to customize row style for each record #8925

Merged
merged 8 commits into from
Aug 10, 2023
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
22 changes: 22 additions & 0 deletions docs/Datagrid.md
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@ Here are all the props accepted by the component:
* [`isRowSelectable`](#isrowselectable)
* [`optimized`](#optimized-better-performance-for-large-tables)
* [`rowStyle`](#rowstyle)
* [`rowSx`](#rowsx)
* [`rowClick`](#rowclick)
* [`size`](#size)
* [`sx`](#sx-css-api)
Expand Down Expand Up @@ -641,6 +642,27 @@ export const PostList = () => (
);
```

## `rowSx`

You can customize the styles of rows and cells in `<Datagrid>` (applied to the `<DatagridRow>` element) based on the record, thanks to the `rowSx` prop, which expects a function. React-admin calls this function for each row, passing the current record and index as arguments. The function should return a Material UI [`sx`](https://mui.com/system/getting-started/the-sx-prop/), which react-admin uses as a `<TableRow sx>` prop.

For instance, this allows to apply a custom background to the entire row if one value of the record - like its number of views - passes a certain threshold.

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

const postRowSx = (record, index) => ({
backgroundColor: record.nb_views >= 500 ? '#efe' : 'white',
});
export const PostList = () => (
<List>
<Datagrid rowSx={postRowSx}>
...
</Datagrid>
</List>
);
```

## `rowClick`

You can catch clicks on rows to redirect to the show or edit view by setting the `rowClick` prop:
Expand Down
21 changes: 20 additions & 1 deletion docs/SimpleList.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ export const PostList = () => (
secondaryText={record => `${record.views} views`}
tertiaryText={record => new Date(record.published_at).toLocaleDateString()}
linkType={record => record.canEdit ? "edit" : "show"}
rowStyle={record => ({ backgroundColor: record.nb_views >= 500 ? '#efe' : 'white' })}
rowSx={record => ({ backgroundColor: record.nb_views >= 500 ? '#efe' : 'white' })}
/>
</List>
);
Expand All @@ -47,6 +47,7 @@ It accepts the following props:
* [`rightAvatar`](#rightavatar)
* [`rightIcon`](#righticon)
* [`rowStyle`](#rowstyle)
* [`rowSx`](#rowsx)
* [`empty`](#empty)

## `leftAvatar`
Expand Down Expand Up @@ -175,6 +176,24 @@ export const PostList = () => (
);
```

## `rowSx`

This optional prop should be a function, which gets called for each row. It receives the current record and index as arguments, and should return a Material UI [`sx`](https://mui.com/system/getting-started/the-sx-prop/). The style object is applied to the `<ListItem>` `sx` prop.

```jsx
import { List, SimpleList } from 'react-admin';

const postRowSx = (record, index) => ({
backgroundColor: record.nb_views >= 500 ? '#efe' : 'white',
});

export const PostList = () => (
<List>
<SimpleList primaryText={record => record.title} rowSx={postRowSx} />
</List>
);
```

## `secondaryText`

See [`primaryText`](#primarytext)
Expand Down
4 changes: 2 additions & 2 deletions examples/demo/src/reviews/ReviewListDesktop.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import {
import ProductReferenceField from '../products/ProductReferenceField';
import CustomerReferenceField from '../visitors/CustomerReferenceField';
import StarRatingField from './StarRatingField';
import rowStyle from './rowStyle';
import rowSx from './rowSx';

import BulkAcceptButton from './BulkAcceptButton';
import BulkRejectButton from './BulkRejectButton';
Expand All @@ -30,7 +30,7 @@ const ReviewsBulkActionButtons = () => (
const ReviewListDesktop = ({ selectedRow }: ReviewListDesktopProps) => (
<Datagrid
rowClick="edit"
rowStyle={rowStyle(selectedRow)}
rowSx={rowSx(selectedRow)}
optimized
bulkActionButtons={<ReviewsBulkActionButtons />}
sx={{
Expand Down
Original file line number Diff line number Diff line change
@@ -1,21 +1,20 @@
import green from '@mui/material/colors/green';
import type { SxProps } from '@mui/material';
import orange from '@mui/material/colors/orange';
import red from '@mui/material/colors/red';
import { useTheme } from '@mui/material/styles';
import { Identifier } from 'react-admin';

import { Review } from './../types';

const rowStyle = (selectedRow?: Identifier) => (record: Review) => {
const theme = useTheme();
const rowSx = (selectedRow?: Identifier) => (record: Review): SxProps => {
let style = {};
if (!record) {
return style;
}
if (selectedRow && selectedRow === record.id) {
style = {
...style,
backgroundColor: theme.palette.action.selected,
backgroundColor: 'action.selected',
};
}
if (record.status === 'accepted')
Expand All @@ -42,4 +41,4 @@ const rowStyle = (selectedRow?: Identifier) => (record: Review) => {
return style;
};

export default rowStyle;
export default rowSx;
10 changes: 8 additions & 2 deletions packages/ra-ui-materialui/src/list/SimpleList/SimpleList.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import * as React from 'react';
import { styled } from '@mui/material/styles';
import type { SxProps } from '@mui/material';
import { isValidElement, ReactNode, ReactElement } from 'react';
import PropTypes from 'prop-types';
import {
Expand Down Expand Up @@ -45,9 +46,10 @@ import { ListNoResults } from '../ListNoResults';
* - rightIcon: same
* - linkType: 'edit' or 'show', or a function returning 'edit' or 'show' based on the record
* - rowStyle: function returning a style object based on (record, index)
* - rowSx: function returning a sx object based on (record, index)
*
* @example // Display all posts as a List
* const postRowStyle = (record, index) => ({
* const postRowSx = (record, index) => ({
* backgroundColor: record.views >= 500 ? '#efe' : 'white',
* });
* export const PostList = () => (
Expand All @@ -58,7 +60,7 @@ import { ListNoResults } from '../ListNoResults';
* tertiaryText={record =>
* new Date(record.published_at).toLocaleDateString()
* }
* rowStyle={postRowStyle}
* rowSx={postRowSx}
* />
* </List>
* );
Expand All @@ -78,6 +80,7 @@ export const SimpleList = <RecordType extends RaRecord = any>(
rightIcon,
secondaryText,
tertiaryText,
rowSx,
rowStyle,
...rest
} = props;
Expand Down Expand Up @@ -139,6 +142,7 @@ export const SimpleList = <RecordType extends RaRecord = any>(
? rowStyle(record, rowIndex)
: undefined
}
sx={rowSx?.(record, rowIndex)}
>
{leftIcon && (
<ListItemIcon>
Expand Down Expand Up @@ -249,6 +253,7 @@ SimpleList.propTypes = {
PropTypes.string,
]),
rowStyle: PropTypes.func,
rowSx: PropTypes.func,
};

export type FunctionToElement<RecordType extends RaRecord = any> = (
Expand All @@ -269,6 +274,7 @@ export interface SimpleListProps<RecordType extends RaRecord = any>
rightIcon?: FunctionToElement<RecordType>;
secondaryText?: FunctionToElement<RecordType> | ReactElement | string;
tertiaryText?: FunctionToElement<RecordType> | ReactElement | string;
rowSx?: (record: RecordType, index: number) => SxProps;
rowStyle?: (record: RecordType, index: number) => any;
// can be injected when using the component without context
resource?: string;
Expand Down
18 changes: 18 additions & 0 deletions packages/ra-ui-materialui/src/list/datagrid/Datagrid.stories.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -149,6 +149,24 @@ export const RowStyle = () => (
</Wrapper>
);

export const RowSx = () => (
<Wrapper>
<Datagrid
rowSx={(record: any) => ({
backgroundColor: record.id % 2 ? 'white' : '#eee',
...(record.year > 1900 && {
'& td.column-year': { color: 'primary.main' },
}),
})}
>
<TextField source="id" />
<TextField source="title" />
<TextField source="author" />
<TextField source="year" />
</Datagrid>
</Wrapper>
);

const CutomBulkActionButtons = () => (
<>
<BulkExportButton />
Expand Down
11 changes: 7 additions & 4 deletions packages/ra-ui-materialui/src/list/datagrid/Datagrid.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ import {
RaRecord,
SortPayload,
} from 'ra-core';
import { Table, TableProps } from '@mui/material';
import { Table, TableProps, SxProps } from '@mui/material';
import clsx from 'clsx';
import union from 'lodash/union';
import difference from 'lodash/difference';
Expand Down Expand Up @@ -51,18 +51,17 @@ const defaultBulkActionButtons = <BulkDeleteButton />;
* - isRowExpandable
* - isRowSelectable
* - optimized
* - rowStyle
* - rowClick
* - size
* - sx
*
* @example // Display all posts as a datagrid
* const postRowStyle = (record, index) => ({
* const postRowSx = (record, index) => ({
* backgroundColor: record.nb_views >= 500 ? '#efe' : 'white',
* });
* export const PostList = () => (
* <List>
* <Datagrid rowStyle={postRowStyle}>
* <Datagrid rowSx={postRowSx}>
* <TextField source="id" />
* <TextField source="title" />
* <TextField source="body" />
Expand Down Expand Up @@ -129,6 +128,7 @@ export const Datagrid: FC<DatagridProps> = React.forwardRef((props, ref) => {
isRowExpandable,
resource,
rowClick,
rowSx,
rowStyle,
size = 'small',
sx,
Expand Down Expand Up @@ -272,6 +272,7 @@ export const Datagrid: FC<DatagridProps> = React.forwardRef((props, ref) => {
hover,
onToggleItem: handleToggleItem,
resource,
rowSx,
rowStyle,
selectedIds,
isRowSelectable,
Expand Down Expand Up @@ -318,6 +319,7 @@ Datagrid.propTypes = {
PropTypes.func,
PropTypes.bool,
]),
rowSx: PropTypes.func,
rowStyle: PropTypes.func,
selectedIds: PropTypes.arrayOf(PropTypes.any),
setSort: PropTypes.func,
Expand Down Expand Up @@ -346,6 +348,7 @@ export interface DatagridProps<RecordType extends RaRecord = any>
isRowExpandable?: (record: RecordType) => boolean;
optimized?: boolean;
rowClick?: string | RowClickFunction | false;
rowSx?: (record: RecordType, index: number) => SxProps;
rowStyle?: (record: RecordType, index: number) => any;
size?: 'medium' | 'small';
// can be injected when using the component without context
Expand Down
8 changes: 6 additions & 2 deletions packages/ra-ui-materialui/src/list/datagrid/DatagridBody.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import * as React from 'react';
import { cloneElement, memo, FC, ReactElement } from 'react';
import PropTypes from 'prop-types';
import { TableBody, TableBodyProps } from '@mui/material';
import { SxProps, TableBody, TableBodyProps } from '@mui/material';
import clsx from 'clsx';
import { Identifier, RaRecord } from 'ra-core';

Expand All @@ -21,6 +21,7 @@ const DatagridBody: FC<DatagridBodyProps> = React.forwardRef(
resource,
row,
rowClick,
rowSx,
rowStyle,
selectedIds,
isRowSelectable,
Expand Down Expand Up @@ -52,7 +53,8 @@ const DatagridBody: FC<DatagridBodyProps> = React.forwardRef(
rowClick,
selectable: !isRowSelectable || isRowSelectable(record),
selected: selectedIds?.includes(record.id),
style: rowStyle ? rowStyle(record, rowIndex) : null,
sx: rowSx?.(record, rowIndex),
style: rowStyle?.(record, rowIndex),
},
children
)
Expand All @@ -79,6 +81,7 @@ DatagridBody.propTypes = {
PropTypes.func,
PropTypes.bool,
]),
rowSx: PropTypes.func,
rowStyle: PropTypes.func,
selectedIds: PropTypes.arrayOf(PropTypes.any),
styles: PropTypes.object,
Expand Down Expand Up @@ -111,6 +114,7 @@ export interface DatagridBodyProps extends Omit<TableBodyProps, 'classes'> {
resource?: string;
row?: ReactElement;
rowClick?: string | RowClickFunction | false;
rowSx?: (record: RaRecord, index: number) => SxProps;
rowStyle?: (record: RaRecord, index: number) => any;
selectedIds?: Identifier[];
isRowSelectable?: (record: RaRecord) => boolean;
Expand Down