reactjssyncfusionej2-syncfusion

SyncFusion DataGrid column selection


I use the DataGrid from SyncFusion for React. They have a selection mode for columns but I can't find a way to get the name of the selected column. Do they have a method that returns the selected column? Something like their getSelectedRecords() method? Or I need to find a way to do it myself?

I tried using their getSelectedRecords() method, but that only returns object of a selected row, doesn't even return the selected cell.


Solution

  • To obtain the field names of the selected columns, you should begin by retrieving the unique identifiers (UIDs) of the selected columns using the “getSelectedColumnsUid“ method. This method returns a string array that contains a list of UIDs for the selected columns. You can then utilize these UIDs to retrieve the corresponding column by utilizing the “getColumnByUid“ method. Once you have the column, you can access the field name using the "field" property. Below is a code snippet that demonstrates how to list the field names of the selected columns:

    [index.js]
    
    function DataGrid() {
    let grid;
     
      function getSelectedColumnNames() {
        return grid
          .getSelectedColumnsUid()
          .map((uid) => grid.getColumnByUid(uid).field);
      }
     
      function btnClick() {
        console.log(getSelectedColumnNames());
      }
     
      return (
        <div className="control-pane">
          <div className="control-section">
            <button className="e-btn e-primary" onClick={btnClick}>
              Get Selected Column Names
            </button>
            <GridComponent
              ref={(g) => (grid = g)}
              dataSource={data}
              allowPaging={true}
              selectionSettings={{
                allowColumnSelection: true,
                type: 'Multiple',
              }}
            >
          .  .  .  .  .
    

    Sample: https://stackblitz.com/edit/react-grid-column-selection

    APIs:

    1. getSelectedColumnsUid: https://ej2.syncfusion.com/react/documentation/api/grid/#getselectedcolumnsuid
    2. getColumnByUid: https://ej2.syncfusion.com/react/documentation/api/grid/#getcolumnbyuid