I am loading a really basic grid using DataGridPro and I need the top row to be selected and highlighted upon loading. I did not see a great example when I tried researching.
This is what my DataGridPro component looks like:
Here is what I have so far:
<DataGridPro
disableMultipleSelection={true}
columns={[
{
field: "startDate",
headerName: "Start Date",
description: "start.",
type: "date",
valueFormatter: ({ value }) => dateFormatter(value),
flex: 0.5,
},
{
field: "endDate",
headerName: "End Date",
description: "end.",
type: "date",
valueFormatter: ({ value }) => (value !== null ? dateFormatter(value) : null),
flex: 0.5,
},
]}
rows={data ? data : null}
></DataGridPro>
I'm not sure what to do since I can't find any examples in their demos or API documentation.
CodePudding user response:
The example that gets you closest to what you want is the
There is some extra complexity in the above code due to useDemoData
loading the data asynchronously. Depending on how your data is passed to the data grid, you may be able to avoid the useEffect
calls and simplify this to something like the following:
import * as React from "react";
import { DataGrid } from "@mui/x-data-grid";
export default function ControlledSelectionGrid({ data }) {
const [selectionModel, setSelectionModel] = React.useState(() => {
const { rows } = data;
const initialSelectionModel = [];
if (rows.length > 0) {
initialSelectionModel.push(rows[0].id);
}
return initialSelectionModel;
});
return (
<div style={{ height: 400, width: "100%" }}>
<DataGrid
checkboxSelection
onSelectionModelChange={(newSelectionModel) => {
setSelectionModel(newSelectionModel);
}}
selectionModel={selectionModel}
{...data}
/>
</div>
);
}