There seems to be a problem with the sorting functionality on the table in React JS,

My React table is functioning well with all columns except for the country name column. I double-checked the API and everything seems to be in order, but I'm stuck on how to troubleshoot this issue.

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

Answer №1

Consider implementing something along these lines:

const sortColumnValues = (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 is crucial to include -1, 0, or 1 in the returns to prevent issues with data types.

For more information on the sort method, you can visit: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort

Answer №2

The issue arises when attempting to sort by country name because it is of type String, causing the callback method logic to fail for sorting Strings.

Trying to subtract two String values will yield NaN.

For guidance on how to properly sort Strings, check out this helpful answer on Stack Overflow: sorting Strings in JavaScript.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the process for integrating custom fields into a product using Stripe, and how can a stock limit be implemented for each customized field?

Currently, as I develop an ecommerce website using Next.js and integrate Stripe for checkout, I've come across the feature of custom fields in Stripe. This feature allows me to add options such as small, medium, and large for clothing sizes. However, ...

Error arises when attempting to pass interface props to a component in a React Typescript application

I am currently delving into the world of React js and typescript. As part of my learning process, I have created a demo application that allows users to input their name and age. The app features an ErrorModal that should pop up on the screen whenever inco ...

Transform Dynamic Array to JSON structure

I am currently developing a feature in my SvelteKit application that allows users to create custom roles for themselves. Users can input a role name and add it to an array, which is then displayed below. https://i.stack.imgur.com/oUPFU.png My goal is to ...

Transform Text into Numeric Value/Date or Null if Text is Invalid

Consider the TypeScript interface below: export interface Model { numberValue: number; dateValue: Date; } I have initialized instances of this interface by setting the properties to empty strings: let model1: Model = { numberValue: +'', ...

Obtain Value from Function Parameter

In my Angular project, I have a function that is called when a button is clicked and it receives a value as an argument. For example: <button (click)="callFoo(bar)">Click Me!</button> The TypeScript code for this function looks like ...

React useCallback causing circular dependency issue

Currently, I am developing a BLE (Bluetooth Low Energy) react provider that allows access to values read over Bluetooth. This provider is designed to automatically reconnect to the BLE device if the connection is lost. Below is a simplified version of th ...

I'm sorry, but we were unable to locate the /bin/sh

After running a command using execSync that runs with sh, I observed the following: spawnSync /bin/sh ENOENT bin is now included in the PATH environment variable. Any ideas on this issue? ...

Tips for effectively packaging the React 17 library alongside the latest JSX transformation feature as an ES Module

I am currently in the process of creating a basic library consisting of React components that I intend to publish as an ES Module package for NPM. With the utilization of React 17, I have incorporated the new JSX transform into my code. To generate the ES ...

Encountering an error while setting up the object spread operator Babel plugin for ES201

Exploring the possibilities of the new ES2018 spread operator for objects led me to discovering a promising NPM package: babel-plugin-transform-object-rest-spread Here's a glimpse of my package.json: // Scripts section "scripts": { "dev": " ...

Encountering the error "Text content does not match" when using Next.js with next-i18next

I have followed the instructions for setting up next-i18next, but I am encountering an error that says "Text content did not match. Server: Testing ZH HANT Client: Testing EN" - even though only English text is displayed on the frontend. I seem to have ove ...

JavaScript enables the deletion of a class

In HTML 2, I am able to show different statements based on the scenario. These statements are styled using the Bootstrap alert class. The goal is to ensure that when new data is sent, any old communication disappears without causing overload on the page. ...

How can I write an if-else statement in JavaScript with Mongoose for MongoDB?

I am facing a challenge where I need to execute a statement only if the object is not null. If the object is null, I should skip executing anything. Is there a correct way to achieve this? I attempted it on MongoDB Playground but unfortunately, it did not ...

5 Creative Techniques for Manipulating Boolean Variables in If Statements

I am receiving a unique custom header value and the values I am getting are accurate. The expected values include: true, false, undefined. However, the response associated with the value: false is incorrect. Code Snippet let deviceStatus = req.headers[ ...

Struggling to determine the expense upon button activation - data remains stagnant

My coding project involves a basic ordering system where users can input an integer, click on an update button, and see the total cost displayed below. Despite my efforts, I've encountered issues with two different methods: Using plain JavaScript for ...

Utilizing React forwardRef with a functional component

Looking at my code, I have defined an interface as follows: export interface INTERFACE1{ name?: string; label?: string; } Additionally, there is a function component implemented like this: export function FUNCTION1({ name, label }: INTERFACE1) { ...

Changing states in next.js is not accomplished by using setState

Struggling to update the page number using setCurrentPage(page) - clicking the button doesn't trigger any state change. Tried various methods without success. Manually modified the number in useState(1) and confirmed that the page did switch. import ...

Creating a formatted JSON string from the data retrieved using a GET request and embedding it into an HTML template to be sent as the

Struggling to send JSON data retrieved from a GET METHOD as an email. The challenge is defining the body of the email using the obtained JSON object. Looking for solutions! Below is a snippet of my code: app.get('/userinfo',(req,res)=>{ ...

The Rails text area fails to load through JavaScript when a line break is detected

My comment form has a feature that displays the content of the text area using js. It functions properly unless a new line is entered in the text area, in which case it does not show up right away. However, after refreshing the page, the comment appears wi ...

Implementing Event Handlers for Multiple Textareas Using Jquery on a Webpage

The functionality of my script is exactly how I want it to be, but I am facing an issue when trying to replicate it on a page. The jQuery code manipulates textarea boxes based on button clicks, however, I now need each textarea box to have its own set of b ...

Creating a custom Angular filter that leverages the power of $http - a

I want to make a retrieval request using $http in AngularJS and then display the obtained result on the front-end. To achieve this, I'm using {{ URL-STRING | iframely }}. 'use strict' angular.module( 'iframely', [] ).filter( &ap ...