18
votes

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

5
Thanks @KrinaSoni , May ik in specific which one can be used for by-default sort ? - Blessy Julie

5 Answers

33
votes

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
                }
            ]
        }
    }
6
votes

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

4
votes

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);
1
votes

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.

0
votes

Thanks a lot ! I sorted out the answer at-last ! About default Sort, I sorted the data of the table descending and got the data by-default as descending . And for clear button How to clear all filters in react-table , please do refer this link !