Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Ability to select only one row at a time (via checkbox) #3664

Open
Ben-CA opened this issue Dec 7, 2024 · 4 comments
Open

Ability to select only one row at a time (via checkbox) #3664

Ben-CA opened this issue Dec 7, 2024 · 4 comments

Comments

@Ben-CA
Copy link

Ben-CA commented Dec 7, 2024

Use case

Currently you can select multiple rows with the checkboxes, which is great. However, sometimes you need to be able to select only one row at a time.

Proposed solution

    rowSelection={'single'} // default being 'multiple'
@Ben-CA
Copy link
Author

Ben-CA commented Dec 7, 2024

I've come up with a work around to only select one row at a time...

  const onSelectedRowsChange = (rows) => {
      const last = (rows.size > 0) ? [...rows].at(-1) : null;
      setSelectedRows(new Set(last));
  };

Used in the grid:

<DataGrid onSelectedRowsChange={onSelectedRowsChange} ...... />

@Ben-CA
Copy link
Author

Ben-CA commented Dec 7, 2024

Note, I'm also using this in conjunction with the following code for the column definitions, such that the checkbox is not displayed in the column header:

const CustomSelectColumn = {
  ...SelectColumn,
  renderHeaderCell: null,
};

Since it would be counter intuitive to have a Select All / Select None when only one row can be selected.

@Ben-CA
Copy link
Author

Ben-CA commented Dec 7, 2024

Also, because there is no function like:

onRowClick={handleRowClick}

Nor a function like:

rowSelectOnClick={true}

A workaround is:

const onCellClick = (event) => {
  if(event.row.categoryId){
    setSelectedRows(new Set(event.row.id)); // where id is your unique row id
  }
};

Used in the grid:

<DataGrid onCellClick={onCellClick} ...... />

@Ben-CA
Copy link
Author

Ben-CA commented Dec 7, 2024

And if you want something that selects/unselects when you click:

  const onCellClick = (event) => {
    if(event.row.id){
      const value = (String(event.row.id) !== String([...selectedRows][0])) ? event.row.id: null;
      setSelectedRows(new Set(value));
    }
  };

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant