reactjsmaterial-uimui-x-data-grid

MUI X Data Grid Pro v5 Highlight First Row Upon Load


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:

DataGridPro Component

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.


Solution

  • The example that gets you closest to what you want is the Controlled selection example. That example demonstrates how to hold the selection in state and pass it as a prop to the data grid. The example does not include how to change the selection from outside the data grid.

    The main thing you need to know is that the selectionModel prop is an array of the selected row ids, so to have the first row start as selected, you need to pass in an array with that row id.

    Below is a modified version of the example from the documentation that demonstrates selecting the first row.

    import * as React from "react";
    import { DataGrid } from "@mui/x-data-grid";
    import { useDemoData } from "@mui/x-data-grid-generator";
    
    export default function ControlledSelectionGrid() {
      const { data, loading } = useDemoData({
        dataSet: "Commodity",
        rowLength: 10,
        maxColumns: 6
      });
      const [selectionModel, setSelectionModel] = React.useState([]);
      const dataRef = React.useRef(data);
      React.useEffect(() => {
        // The ref allows me to leave `data` out of the dependency array
        // of the next effect, so that it is only triggered by changes
        // to the `loading` state.
        dataRef.current = data;
      });
      React.useEffect(() => {
        if (!loading) {
          const { rows } = dataRef.current;
          if (rows.length > 0) {
            setSelectionModel([rows[0].id]);
          }
        }
      }, [loading]);
    
      return (
        <div style={{ height: 400, width: "100%" }}>
          <DataGrid
            checkboxSelection
            onSelectionModelChange={(newSelectionModel) => {
              setSelectionModel(newSelectionModel);
            }}
            selectionModel={selectionModel}
            {...data}
          />
        </div>
      );
    }
    

    Edit ControlledSelectionGrid Material Demo (forked)

    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>
      );
    }
    

    Edit ControlledSelectionGrid Material Demo (forked)