Home > Software design >  How to sort JSX elements from JSON values
How to sort JSX elements from JSON values

Time:04-20

What I Want to Do:

I want to render a list of elements using .map, then sort by most recent on top. I've tried adding .sort and .filter before rendering the element, but it doesn't seem to be working. I've done some quick Google searches, but came across posts which don't seem relevant to what i'm trying to do. (or it's just me).

I want to sort by date, with the most recent on top.

Render Component:

import React from "react";
import TransactionEntry from "./TransactionEntry";

function Transactions({ transactionList }) {
  return (
    <div className="flex flex-col items-start justify-start w-full h-[520px] overflow-auto gap-3 no-scrollbar">
      {transactionList.map((transaction) => {
        return (
          <TransactionEntry
            id={transaction.id}
            retailer={transaction.retailer}
            category={transaction.category}
            price={transaction.price}
            dateAdded={transaction.dateAdded}
          />
        );
      })}
    </div>
  );
}

export default Transactions;

Data Structure:

[
    {
        "id": "ts001",
        "category": "Category",
        "retailer": "Retailer",
        "price": 1.99,
        "dateAdded": "04/02/01"
    },
    {
        "id": "ts002",
        "category": "Category",
        "retailer": "Retailer",
        "price": 13.99,
        "dateAdded": "04/02/04"
    },
    {
        "id": "ts003",
        "category": "Category",
        "retailer": "Retailer",
        "price": 119.99,
        "dateAdded": "04/02/09"
    }
]

CodePudding user response:

You can sort before mapping in this way

{transactionList.sort((a, b) => new Date(a.dateAdded) - new Date(b.dateAdded)).map((transaction) => {
        return (
          <TransactionEntry
            id={transaction.id}
            retailer={transaction.retailer}
            category={transaction.category}
            price={transaction.price}
            dateAdded={transaction.dateAdded}
          />
        );
      })}
  • Related