3

I am currently creating a React web application and am using a DataGrid from google's Material-UI. The grid renders based on a selection of a select list(i.e if the select list is of fruits, and the user selects apples, a related DataGrid will render with info about apples. If the user selects another fruit, another related datagrid will render, similar to a Master/Detail relationship).

Since DataGrid offers row selection, I would like to have the first row preselected every time the grid renders, including when the user first enters the page. Currently, the grid renders without any rows selected, and requires the user to click on a row in order to make a selection. I saw on that controlled selection may be possible(https://material-ui.com/components/data-grid/selection/#controlled-selection) although the documentation doesn't explain this in great detail.

I also tried a hack from stackOverflow(Can I initialize the checkbox selection in a material-ui DataGrid?) but that did not seem to work either. I feel like this feature is easier to implement than i am making it out, and should be included out of the box. Thank you in advance!

Edit: Adding a sample code for reference.

import * as React from 'react';
import { DataGrid } from '@material-ui/data-grid';
import { useDemoData } from '@material-ui/x-grid-data-generator';

export default function SingleRowSelectionGrid() {
  
const [selectedRowID, setSelectedRowID] = useState(0);


  const columns = [
    { field: "id", headerName: "ID", width: 70 },
    { field: "firstName", headerName: "First name", width: 130 },
    { field: "lastName", headerName: "Last name", width: 130 },
    {
      field: "age",
      headerName: "Age",
      type: "number",
      width: 90,
    },

  ];

  const rows = [
    { id: 1, lastName: "Snow", firstName: "Jon", age: 35 },
    { id: 2, lastName: "Lannister", firstName: "Cersei", age: 42 },
    { id: 3, lastName: "Lannister", firstName: "Jaime", age: 45 },
    { id: 4, lastName: "Stark", firstName: "Arya", age: 16 },
    { id: 5, lastName: "Targaryen", firstName: "Daenerys", age: null },
    { id: 6, lastName: "Melisandre", firstName: null, age: 150 },
    { id: 7, lastName: "Clifford", firstName: "Ferrara", age: 44 },
    { id: 8, lastName: "Frances", firstName: "Rossini", age: 36 },
    { id: 9, lastName: "Roxie", firstName: "Harvey", age: 65 },
  ];



  return (
    <div style={{ height: 400, width: '100%' }}>
      <DataGrid 
                rows={rows} 
                columns={columns}
                onSelectionChange={(selectedRow) => {
                        setSelectedRowID(selectedRow.rowIds[0])}}
                  
      />
    </div>
  );
}
Lucas
  • 31
  • 1
  • 3
  • Can you provide your code so that we can see what we are working with (you can create a basic example and remove sensitive or proprietary data)? I need an example of what you are trying to do along with your explanation of what you are trying to accomplish. That will help me be able to see if I can help you identify the problem. – Jason Bellomy Feb 11 '21 at 16:38
  • @JasonBellomy Sure! I updated the post to include an example of my code. Thanks in advance! – Lucas Feb 11 '21 at 18:03

3 Answers3

9

You need to use the selectionModel prop in the DataGrid component.

...
      <DataGrid
        checkboxSelection
        rows={rows} 
        columns={columns}
        onSelectionChange={(newSelection) => {
          setSelection(newSelection.rowIds);
        }}
        selectionModel={selectedRows}
      />
...
Ryan Carville
  • 355
  • 7
  • 15
1

Based on your code, and looking at the Material-UI DataGrid documentation, it looks like you are missing the checkboxSelection property.

Try this and see if it works:

import * as React from 'react';
import { DataGrid } from '@material-ui/data-grid';

const columns = [
  { field: "id", headerName: "ID", width: 70 },
  { field: "firstName", headerName: "First name", width: 130 },
  { field: "lastName", headerName: "Last name", width: 130 },
  {
    field: "age",
    headerName: "Age",
    type: "number",
    width: 90
  }
];

const rows = [
  { id: 1, lastName: "Snow", firstName: "Jon", age: 35 },
  { id: 2, lastName: "Lannister", firstName: "Cersei", age: 42 },
  { id: 3, lastName: "Lannister", firstName: "Jaime", age: 45 },
  { id: 4, lastName: "Stark", firstName: "Arya", age: 16 },
  { id: 5, lastName: "Targaryen", firstName: "Daenerys", age: null },
  { id: 6, lastName: "Melisandre", firstName: null, age: 150 },
  { id: 7, lastName: "Clifford", firstName: "Ferrara", age: 44 },
  { id: 8, lastName: "Frances", firstName: "Rossini", age: 36 },
  { id: 9, lastName: "Roxie", firstName: "Harvey", age: 65 }
];

export default function SingleRowSelectionGrid() {
  const [selectedRows, setSelection] = React.useState([]);

  return (
    <div style={{ height: 400, width: '100%' }}>
      <DataGrid
        checkboxSelection
        rows={rows} 
        columns={columns}
        onSelectionChange={(newSelection) => {
          setSelection(newSelection.rowIds);
        }}
      />
      {
          selectedRows.map(row =>
              <span>{row}<span>
          )
      }
    </div>
  );
}
Jason Bellomy
  • 442
  • 2
  • 7
  • Thanks for the reply. I tried the code above and unfortunately it did not work in my test environment. I did modify my code in the question to in order to better represent my scenario. Let me know if I can further clarify anything. – Lucas Feb 12 '21 at 15:31
  • So I found some documentation on the Material-UI Datagrid web page (https://material-ui.com/components/data-grid/selection/#ControlledSelectionGrid.js). You need to add the checkboxSelection prop, and then your onSelection was correct. Try my updated code and see if that works. – Jason Bellomy Feb 12 '21 at 15:58
  • Thank you for taking another look. I went ahead and tried your code but it is not achieving what I am trying to achieve. I want a preselect row to be selected when the user first enters the page. It should always be the first row selected when they first enter the page. The selection must show on the table as well. – Lucas Feb 17 '21 at 21:26
  • @Lucas - I'm curious if you were ever able to figure out your problem or if you still need help with this? Since this is so long ago, I wanted to check on the status and if you solved the problem. If so, what was the issue and how did you solve it? – Jason Bellomy Jan 27 '22 at 15:52
1

Today I had a similar problem. The above mentioned methods work, unless you're fetching data/rows from different sources like ParentPage/State & API. In this code, list is passed by another page as state, so it's instant, while movies are fetched from API, so it takes longer. The problem is when content passed to selectionModel prop, there are no rows/movies to be rendered. I think then Material-UI Data Grid sets content = []. The solution is in the code.

export default function ListItem() {
  const location = useLocation();
  const { dispatch } = useContext(ListsContext);
  const [list, setList] = useState(location.state.list);
  const { movies, dispatch: dispatchMovies } = useContext(MoviesContext);
  const [content, setContent] = useState(list.content); 
 

 useEffect(() => {
   getMovies(dispatchMovies).then((elem) => setContent(list.content));
   }, [dispatchMovies, list]);

 <DataGrid
   rows={movies}
   disableSelectionOnClick
   columns={columns}
   rowsPerPageOptions={[10]}
   checkboxSelection
   onSelectionModelChange={(item) => {setContent(item);}}
   selectionModel={content}
   />
TyposBro
  • 11
  • 1
  • 3