How to set a default sorting in a react table?

6.5k Views Asked by At

I am trying to make a default sorting in for all columns in react-table v7 and show only ascending and descending, I've tried the following

useTable(
    {
      columns,
      data,
      initialState: {
        sortBy: [
          columns.map((one) => {
            return {
              id: one.accessor ? one.accessor : one.id,
              desc: true,
            };
          }),
        ],
)

This does change order by default in table, but sorting icons don't appear on columns which I wrote like this

                 {column.isSorted ? (
                        column.isSortedDesc ? (
                          <ExpandLessIcon
                            fontSize="large"
                            style={{
                              transition: "250ms transform",
                              marginLeft: "7px",
                              fontSize: "20px",
                            }}
                            color="disabled"
                          ></ExpandLessIcon>
                        ) : (
                          <ExpandMoreIcon
                            fontSize="large"
                            style={{
                              transition: "250ms transform",
                              marginLeft: "7px",
                              fontSize: "20px",
                            }}
                            color="disabled"
                          ></ExpandMoreIcon>
                        )
                      ) : (
                        ""
                      )}

and column.isSorted is still false when I console log. Can someone help me out with this issue ?

1

There are 1 best solutions below

1
On BEST ANSWER

Array.map returns a new array which makes sortBy array to have another array and it's causing issue. This works

        sortBy: columns.map((one) => {
          return {
            desc: false,
            id: one.accessor ? one.accessor : "",
          };
        }),