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

[RFR] Allow override of Datagrid Body and Row elements #2575

Merged
merged 1 commit into from
Nov 27, 2018
Merged

Conversation

fzaninotto
Copy link
Member

By default, <Datagrid> renders its body using <DatagridBody>, an internal react-admin component. You can pass a custom component as the row prop to override that default. And by the way, <DatagridBody> has a row property set to <DatagridRow> by default for the same purpose. <DatagridRow> receives the row record, the resource, and a copy of the datagrid children. That means you can create a custom datagrid logic without copying several components from the react-admin source.

For instance, to show the selection checkbox only for records that have a selectable field set to true, you can override <DatagridRow> and <DatagridBody> as follows:

// in src/PostList.js
import { Datagrid, DatagridBody, List, TextField } from 'react-admin';
import TableCell from '@material-ui/core/TableCell';
import TableRow from '@material-ui/core/TableRow';
import Checkbox from '@material-ui/core/Checkbox';

const MyDatagridRow = ({ record, resource, id, onToggleItem, children, selected, basePath }) => (
    <TableRow key={id}>
        {/* first column: selection checkbox */}
        <TableCell padding="none">
            {record.selectable && <Checkbox
                checked={selected}
                onClick={() => onToggleItem(id)}
            />}
        </TableCell>
        {/* data columns based on children */}
        {React.Children.map(children, field => (
            <TableCell key={`${id}-${field.props.source}`}>
                {React.cloneElement(field, {
                    record,
                    basePath,
                    resource,
                })}
            </TableCell>
        ))}
    </TableRow>
)

const MyDatagridBody = props => <DatagridBody {...props} row={<MyDatagridRow />} />;
const MyDatagrid = props => <Datagrid {...props} body={<MyDatagridBody />} />;

const PostList = props => (
    <List {...props}>
        <MyDatagrid>
            <Textfield source="title" />
            ...
        </MyDatagrid>
    </List>
)

export default PostList;

@djhi djhi added this to the 2.5.0 milestone Nov 27, 2018
@djhi djhi merged commit 69da6e2 into next Nov 27, 2018
@djhi djhi deleted the customize-datagrid branch November 27, 2018 08:20
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants