🐛(react) support nested field in DataGrid

It was previously needed to use renderCell to be able to use nested
fields, which was not handy.

Resolve #62
This commit is contained in:
Nathan Vasse
2023-05-22 16:45:37 +02:00
committed by NathanVss
parent 1ff37cf12f
commit 9127fd803c
3 changed files with 57 additions and 8 deletions

View File

@@ -0,0 +1,5 @@
---
"@openfun/cunningham-react": patch
---
support nested field in DataGrid

View File

@@ -214,6 +214,7 @@ describe("<DataGrid/>", () => {
});
});
});
it("should render custom cells", async () => {
const database = Array.from(Array(10)).map(() => ({
id: faker.string.uuid(),
@@ -261,6 +262,7 @@ describe("<DataGrid/>", () => {
});
});
});
it("should render highlighted column", async () => {
const database = Array.from(Array(10)).map(() => ({
id: faker.string.uuid(),
@@ -323,4 +325,43 @@ describe("<DataGrid/>", () => {
);
});
});
it("should render nested fields", async () => {
const database = Array.from(Array(10)).map(() => ({
id: faker.string.uuid(),
sub: {
name: faker.person.fullName(),
},
}));
const Component = () => {
return (
<CunninghamProvider>
<DataGrid
columns={[
{
field: "sub.name",
headerName: "Name",
},
]}
rows={database}
/>
</CunninghamProvider>
);
};
render(<Component />);
const table = screen.getByRole("table");
const ths = getAllByRole(table, "columnheader");
expect(ths.length).toBe(1);
expect(ths[0].textContent).toEqual("Name");
database.forEach((row) => {
const element = screen.getByTestId(row.id);
const tds = getAllByRole(element, "cell");
expect(tds.length).toBe(1);
expect(tds[0].textContent).toEqual(row.sub.name);
});
});
});

View File

@@ -5,7 +5,11 @@ import {
PaginationState,
SortingState,
} from "@tanstack/react-table";
import React from "react";
import React, { ReactNode } from "react";
import {
ColumnDefBase,
DisplayColumnDef,
} from "@tanstack/table-core/src/types";
import { Checkbox } from ":/components/Forms/Checkbox";
import { PaginationProps } from ":/components/Pagination";
import { Column, Row, SortModel } from ":/components/DataGrid/index";
@@ -28,17 +32,16 @@ export const useHeadlessColumns = ({
id: column.field ?? "actions",
enableSorting: column.enableSorting,
header: column.headerName,
cell: (info: CellContext<Row, any>) => {
if (column.renderCell) {
return column.renderCell({ row: info.row.original });
}
return info.row.original[info.column.id];
},
};
if (column.field) {
return columnHelper.accessor(column.field, opts);
}
return columnHelper.display(opts);
return columnHelper.display({
...opts,
cell: (info) => {
return column.renderCell!({ row: info.row.original });
},
});
});
if (enableRowSelection) {
headlessColumns = [