reactjsreact-functional-componentprimereact

How can I customize the default sorting behavior in a PrimeReact DataTable?


I want to enable sorting with null values in PrimeReact. Currently, null values are always placed at the bottom by default, similar to Excel's behavior.

Previously, sorting was working as shown in this PR, but I'd like to revert to the old behavior. How can I achieve this?

In the example from the link I mentioned, when sorting the Name column, empty values are moved to the bottom. Upon the next sorting, they remain at the bottom and don't come to the top. I want to override this behavior.

Code Link: https://stackblitz.com/edit/bxt2v3pi?file=src%2Fservice%2FProductService.jsx


Solution

  • Use Null Sort Order configuration to control how the null values are sorted. If you set it to -1, then you can have the null values move to top/bottom when you sort the column.

    From the docs:

    Determines how null values are sorted. The default value of 1 means sort like Excel with all NULL values at the bottom of the list. A value of -1 sorts NULL at the top of the list in ascending mode and at the bottom of the list in descending mode.

    Example:

    import { PrimeReactProvider } from 'primereact/api';
    
    export default function MyApp({ Component }) {
        const value = {
            nullSortOrder: -1
        };
    
        return (
            <PrimeReactProvider value={value}>
                <App />
            </PrimeReactProvider>
        );
    }
    

    Check this working StackBlitz demo.