How to do default sorting in react-table How to do default sorting in react-table reactjs reactjs

How to do default sorting in react-table


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


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 mehttps://codesandbox.io/s/stupefied-hoover-ibz6f


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