0

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

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.