reactjstypescriptgenericsreact-data-table-component

How to type a sortFunction with the correct definitions for react-data-table-component?


I want to type this custom method for sorting in react-data-table-component custom component, I'm not sure what should be done in the selector:

const customSort = (rows: IAlergia[], selector: any //WANT TO REMOVE ANY, direction: string)

Full code:

interface IAlergia {
  AlergiaId: number;
  Descripcion: string;
  Reaccion: string;
  Estatus: string;
  Comprador: string;
  CompradorId: number;
}

const Alergia = () => {
    
  
    //Custom sort since the component uses Array.Sort and it does not take in account the lowercase sorting...
    const customSort = (rows: IAlergia[], selector: any, direction: string) => {
        return rows.sort((a, b) => {
            // use the selector to resolve your field names by passing the sort comparators
            const aField = selector(a).toLowerCase();
            const bField = selector(b).toLowerCase();
    
            let comparison = 0;
    
            if (aField > bField) {
                comparison = 1;
            } else if (aField < bField) {
                comparison = -1;
            }
    
            return direction === 'desc' ? comparison * -1 : comparison;
        });
    };
        
    

    return(
        <DataTable columns={columns} data={options} sortFunction={customSort}/>
    )
}

export default Alergia;

Solution

  • I don't know if your question is still relevant but the correct type for selector attribute is Selector<YourRowType>.

    Don't forget to import the type:

    import DataTable, { Selector } from "react-data-table-component";