T
TanStack3y ago
yappiest-sapphire

useSortBy sets descending on adjacent column not column that is clicked

Hello, I am using react-table to create a basic datatable with column sorting. I am adding an aria-sort attribute to the column headers (<th>) tags. What I am trying to do is make sure that when someone decides to sort a specific column, when isSortedDesc is true, the aria-sort attribute should get set to aria-sort='descending' otherwise it should be set to aria-sort='ascending' and if isSorted is true then set aria-sort='none' I am able to set aria-sort correctly based on the conditions, but the problem I'm running in to is that when I click on "First Name" it doesn't change the aria-sort attribute for that column but instead changes the aria-sort attribute for "Last Name" and so on. Any ideas why this is happening? You can see the problem in this code sandbox. Inspect the <thead> and you should see the aria-sort attribute on each <th>. Try to sort by "First Name" and you will see that the aria-sort attribute on "Last Name" changes. https://codesandbox.io/s/happy-sammet-677rfi?file=/src/App.js
1 Reply
conscious-sapphire
conscious-sapphire3y ago
Hi, I took a look at you code sandbox: I don't know why you rely on sortDirection variable since you have all the info you need right from the column.isSorted/isSortedDesc (like you said in your question). I tried replacing it with the variables I just mentioned and it seems to work just fine. Here's why the aria-sort was set on the wrong column: You used sortDirection to decide what to display, but you set that variable inside content of the column ({(sortDirection = "descending")}): this approach is unreliable and as you've seen can make things very confusing. You should never mutate the data inside interpolation. What happened is that the value of the variable was set after the aria-sort had been calculated, so the next column found the value that pertained to the previous column(yes, that wasn't just a problem with First Name, all columns changed the one after them).

Did you find this page helpful?