Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do default sorting in react-table

I am using react-table v7 https://www.npmjs.com/package/react-table for creating tables.

  1. I am able to do sorting to all the columns by referring this example of sorting https://codesandbox.io/s/github/tannerlinsley/react-table/tree/master/examples/sorting . Now I dont want all columns to sort but some specfic columns and I want to sort 2 columns by default descending. Can someone please help me with this.

  2. After applying filters to the table I want to clear all the applied filters. Can someone please help in solving this issue too ?

Thank you

like image 920
Blessy Julie Avatar asked Feb 06 '20 06:02

Blessy Julie


4 Answers

The other answer given was for react-table that didn't use react hooks (< v7). In order to sort a column (or columns) when the table is built, you just have to set the sortBy array on the initialState in the useTable hook.

const {
    getTableProps,
    getTableBodyProps,
    ...
} = useTable(
    {
        columns,
        ....,
        initialState: {
            sortBy: [
                {
                    id: 'columnId',
                    desc: false
                }
            ]
        }
    }
like image 117
Chuck L Avatar answered Oct 27 '22 09:10

Chuck L


you can pass sorted options to ReactTable please try with below code. And for clear try with button click call clear function.

  constructor(props) {
    super(props);
    this.state = {
      sortOptions: [{ id: 'age', desc: true },{ id: 'visits', desc: true }],
     }
  }

 <Table 
    sorted={this.state.sortOptions}
    onSortedChange={val => {
    this.setState({ sortOptions: val }) }}
    columns={columns} 
    data={data} />

It works for me https://codesandbox.io/s/stupefied-hoover-ibz6f

like image 29
Oshini Avatar answered Oct 27 '22 11:10

Oshini


I had a slightly different use case and wanted to get multi-sorting by default on initial load, but then also keep that sorting order behind any future sorts

sandbox example here: https://codesandbox.io/s/goofy-shadow-9tskr?file=/src/App.js

The trick is NOT using the built in getSortByToggleProps() and instead adding your own onClick that uses the setSortBy func.

Below code inspired from @khai nguyen's answer

import React from 'react'
import { useTable, useSortBy } from 'react-table';

function Table({ columns, data, sortBy ...rest }) {
    const {
        getTableProps,
        getTableBodyProps,
        headerGroups,
        rows,
        prepareRow,
        setSortBy,
    } = useTable({
        columns,
        data,
        initialState: {sortBy}
        })
    }, useSortBy); 

Then in your column header element:

     ...PREV_TABLE_CODE
{headerGroup.headers.map(column => (
         <th
         {...column.getHeaderProps()}
         onClick={() => handleMultiSortBy(column, setSortBy, sortBy)}
          >
         {column.render( 
REST_TABLE_CODE....

and the handleMultiSortByCode (my custom function, not from react-table):

isSortedDesc can be either true/false/undefined

export const handleMultiSortBy = (column, setSortBy, meinSortBy) => {
  //set sort desc, aesc or none?
  const desc =
    column.isSortedDesc === true
      ? undefined
      : column.isSortedDesc === false
      ? true
      : false;
  setSortBy([{ id: column.id, desc }, ...meinSortBy]);
};
 

Note: The default toggleSortBy() func had a e.persist() in it. I'm not sure what function it served, but not using it doesn't have any ill effects that I've noticed - the stock multi-sort doesn't work (holding shift) but adding it back didn't fix that. Suspect you might need the stock toggleSort for that.

like image 29
sirclesam Avatar answered Oct 27 '22 11:10

sirclesam


You need to import the 'useSortBy' hook provided by react-table to make it work as expected.

import React from 'react'
import { useTable, useSortBy } from 'react-table';

function Table({ columns, data, ...rest }) {
    const {
        getTableProps,
        getTableBodyProps,
        headerGroups,
        rows,
        prepareRow,
    } = useTable({
        columns,
        data,
        ...(rest.initialState && {
            initialState: rest.initialState
        })
    }, useSortBy);
like image 31
Khai Nguyen Avatar answered Oct 27 '22 09:10

Khai Nguyen