How do I make a React table sortable by every column?

1k Views Asked by At

I have a table, and I want to make it so that the user can sort it by any column. Here is my code:-

import React, { useState } from "react";
import "bootstrap/dist/css/bootstrap.min.css";
import { Table } from "reactstrap";
import { BootstrapTable } from "react-bootstrap-table-next";

function Results(props) {
  var results = props.results;
  console.log(results);
  const [sresults, setSResults] = useState(results);
  const sorter = key =>
    sresults.sort((a, b) => {
      console.log("I am In THE SORTER");
      if (a[key] < b[key]) {
        console.log("RETURNING -1");
        return -1;
      }
      if (a[key] > b[key]) {
        console.log("RETURNING 1");
        return 1;
      }
      console.log("RETURNING 0");
      return 0;
    });
  if (!props.results) return "no data";
  if (!Array.isArray(props.results)) return "results are not array";
  function rows() {
    let result = sresults.map((result, index) => {
      return (
        <tr key={result.Book_Name}>
          <th scope="row">{index}</th>
          <td>{result.Book_Name}</td>
          <td>{result.Author}</td>
          <td>{result.S_no}</td>
          <td>{result.Series_Name}</td>
          <td>{result.Fiction_Non_fiction_Companion_Prequel}</td>
          <td>{result.Genre}</td>
          <td>{result.Kindle_Real}</td>
        </tr>
      );
    });
    return result;
  }
  function ssorter(key) {
    setSResults(sorter(key));
    console.log(sresults);
  }
  return (
    <Table hover bordered responsive>
      <thead>
        <tr>
          <th>{"S.no of the Books Found"}</th>
          <th>{"Book Name"}</th>
          <th>{"Author"}</th>
          <th>
            {"S.no"}
            <button onClick={() => ssorter("S_no")} />
          </th>
          <th>{"Series Name"}</th>
          <th>{"Fiction/Non fiction/Companion/Prequel"}</th>
          <th>{"Genre"}</th>
          <th>{"Kindle or Real"}</th>
        </tr>
      </thead>
      <tbody>{rows()}</tbody>
    </Table>
  );
}

export default Results;


I tried react-bootstrap-table-next, but I get a fatal error, saying that it expects a string. The tutorial I followed for react-bootstrap-table-next is here.

Thanks in advance, and please let know if you need any more details.

Edit:The state changes. I have confirmed this. But, the page doesn't rerender.

1

There are 1 best solutions below

4
On

attach to each TH a onClick function. Make use of useState. Put your results into this state. Then on onClick trigger sort basing on table column. i.e.

const sorter = key => results.sort((a, b) => {
  if(a[key] < b[key]) { return -1; }
  if(a[key] > b[key]) { return 1; }
  return 0;
})

with onClick={() => setResults(sorter('Book_Name'))} it's just some crude code, it could be improved but should give you idea. Now of course you need to display this somehow on table row headers (i.e. arrows) and implement sort direction (ASC, DESC).