🐛(react) allow to set column size for data grid without header

Currently, to set the width of column we define a width to the
corresponding header cell. But DataGrid components allows to not render
header rows so in this case, the size is not set. In order to fix that,
if header is not rendered, we set width of cell to the corresponding
column.
This commit is contained in:
jbpenrath
2024-05-27 12:17:20 +02:00
committed by Jean-Baptiste PENRATH
parent 79df983d0c
commit b6c0565958
3 changed files with 62 additions and 1 deletions

View File

@@ -1,7 +1,7 @@
import React, { useEffect, useState } from "react";
import { faker } from "@faker-js/faker";
import { act, render, screen, waitFor } from "@testing-library/react";
import { getAllByRole, getByRole } from "@testing-library/dom";
import { getAllByRole, getByRole, queryAllByRole } from "@testing-library/dom";
import userEvent from "@testing-library/user-event";
import { usePagination } from ":/components/Pagination";
import { DataGrid, SortModel } from ":/components/DataGrid/index";
@@ -441,4 +441,52 @@ describe("<DataGrid/>", () => {
expect(ths[0].style.width).toEqual("50px");
expect(ths[1].style.width).toEqual("");
});
it("should render column with specific width even without header", async () => {
const database = Array.from(Array(10)).map(() => ({
id: faker.string.uuid(),
name: faker.person.fullName(),
email: faker.internet.email(),
}));
const Component = () => {
return (
<CunninghamProvider>
<DataGrid
displayHeader={false}
columns={[
{
field: "name",
size: 50,
},
{
field: "email",
headerName: "Email",
},
]}
rows={database}
/>
</CunninghamProvider>
);
};
render(<Component />);
const table = screen.getByRole("table");
const ths = queryAllByRole(table, "columnheader");
// No header should be displayed.
expect(ths.length).toBe(0);
database.forEach((data) => {
// Each data should have a row.
const element = screen.getByTestId(data.id);
// Then cells containing "name" should have a width of 50px.
let td = getByRole(element, "cell", { name: data.name });
expect(td.style.width).toEqual("50px");
td = getByRole(element, "cell", { name: data.email });
expect(td.style.width).toEqual("");
});
});
});

View File

@@ -282,6 +282,13 @@ export const DataGrid = <T extends Row>({
} else {
highlight = !!columns[i].highlight;
}
const style: CSSProperties = {};
if (displayHeader === false) {
const column = columns[i];
if (column && typeof column.size === "number") {
style.width = `${column.size}px`;
}
}
return (
<td
key={cell.id}
@@ -292,6 +299,7 @@ export const DataGrid = <T extends Row>({
"c__datagrid__row__cell--select":
cell.column.id === "select",
})}
style={style}
>
{flexRender(
cell.column.columnDef.cell,