javascriptreactjsgridag-gridag-grid-react

Fix a row while sorting in ag grid react


There is a dropdown and based on the values of the dropdown I am sorting the ag grid here but I want to fix a row at top when doing sorting with id 956306 how can I achieve it ??

const handleApplyQuickSort = (selectedSort: string) => {
    const colId = SORT_MAP[selectedSort];
    if (colId && gridRef.current) {
      gridRef.current?.columnApi?.applyColumnState({
        state        : [{ colId: colId, sort: 'desc' }],
        defaultState : { sort: null },
      });
      initialSortAppliedRef.current = true;
      const rowIndexToKeepOnTop = gridRef?.current?.props?.rowData?.findIndex((row:UIModel) => String(row.id) === '956306');
      if (rowIndexToKeepOnTop !== -1 && rowIndexToKeepOnTop) {
        const rowToKeepOnTop = gridRef?.current?.props?.rowData?.splice(rowIndexToKeepOnTop, 1)[0];
        gridRef?.current?.props?.rowData?.unshift(rowToKeepOnTop);
      }    
    }
  };

Solution

  • Use the comparator for custom sorting like so

    const gridOptions = {
        columnDefs: [
            {
                field: 'age',
                // simple number comparator
                comparator: (valueA, valueB, nodeA, nodeB, isDescending) => valueA - valueB
            },
            {
                field: 'name',
                // simple string comparator
                comparator: (valueA, valueB, nodeA, nodeB, isDescending) => {
                    if (nodeA.data.id === '956306') return -Number.NEGATIVE_INFINITY;
                    if (valueA == valueB) return 0;
                    return (valueA > valueB) ? 1 : -1;
                }
            }
        ],
    
        // other grid options ...
    }