tomgru23
tomgru23

Reputation: 109

React Js - Table doesn't sort names

So I've got this table in React. It works fine with all the columns except the one with the country name. I checked API so className definitely matches with it and I am a bit clueless how to fix it.

const Table = () => {
    const[country, setCountry] = useState([]);
    const[toggle, setToggle] = useState(true);

    const sortColumnNumber = (sort, columnName, data) => {
      data = data.sort((a, b) => {
        return sort ? b[columnName] - a[columnName] : a[columnName] - b[columnName];
      });
    }

    useEffect(() => {
        const loadData = async() => {
          await fetch('https://api.covid19api.com/summary')
          .then(response => response.json())
          .then(data => {
          const stats = data.Countries;
          sortColumnNumber(toggle, 'TotalConfirmed', stats)
          setCountry(stats);
          })
          }
          loadData();
    }, []);

    return(
        <React.Fragment>
            <table className="table table-bordered table-stripped">
        <thead >
        <tr onClick={(e) =>{
            setToggle(!toggle);
            sortColumnNumber(toggle, e.target.className, country);
        }} style={{cursor: "pointer"}} className="thead-dark">
          <th className="Country" scope="col">Country</th>
          <th className="TotalConfirmed" scope="col">Total Cases</th>
          <th className="NewConfirmed" scope="col">New Cases</th>
          <th className="NewDeaths" scope="col">New Deaths</th>
          <th className="TotalDeaths" scope="col">Total Deaths </th>
          <th className="TotalRecovered" scope="col">Total Recovered </th>
        </tr>
        </thead>
          <tbody>
          <CountryStats country={country} />
          </tbody>
          </table>
          </React.Fragment>
    )
}

Upvotes: 0

Views: 48

Answers (2)

Gabriel Willemann
Gabriel Willemann

Reputation: 1921

Try something like that:

const sortColumnNumber = (sort, columnName, data) => {
  data = data.sort((a, b) => {
    let [first, second] = sort ? [a, b] : [b, a];

    if (first[columnName] < second[columnName]) return -1;
    if (first[columnName] > second[columnName]) return 1;
    return 0;
  });
};

It's important to return -1 or 0 or 1 to avoid problem with data types.

See more about sort method in this link: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort

Upvotes: 2

Rajeev Singh
Rajeev Singh

Reputation: 3332

It doesn't work with country name because it is a String type and your callback method logic will not work for sorting Strings.

Subtracting two String values results in NaN.

Refer to this SO answer for sorting Strings.

Upvotes: 0

Related Questions